1

How I can restart fmax counting when a condition occurs?
I got two numpy arrays, I call np.fmax.accumulate on the first, but when it touches the second array value at the same index, it should turns to the first array value at the same index, and then reset and restart maximum accumulating.
Example:

array2 = np.array([4,4,4,3,5,2,1])
array1 = np.array([1,2,3,2,4,1,0.5])
max = np.fmax.accumulate(array1)

                   0   1   2   3   4   5   6
array2             4   4   4   3   5   2   1
array1             1   2   3   2   4   1  0.5   
max                1   2   3   3   4   4   4

expected output    1   2   3   2   4   1  0.5
                               ^       ^   ^

Can I do this using JUST numpy or at least NO LOOPS?

JC FIVE
  • 33
  • 5
  • What do you mean by "when it touches the second array value"? Can you express that in logical terms? – Bill Oct 13 '22 at 15:37
  • I mean when `expected output >= array2` @bill – JC FIVE Oct 13 '22 at 16:00
  • 1
    Good question. I have previously wondered if it's possible to use np.accumulate with a function having more than one input variable but based on the answers to [this question](https://stackoverflow.com/questions/4407984/is-it-possible-to-vectorize-recursive-calculation-of-a-numpy-array-where-each-el/62736143#62736143) I concluded it isn't. However, in your case `array2` is pre-computed so I wonder if there is a way to pass the whole array into a custom [ufunc](https://numpy.org/doc/stable/reference/ufuncs.html) and then use `accumulate` on it. – Bill Oct 14 '22 at 17:34

1 Answers1

1
output = np.where(max < array2, max, array1)
[1.  2.  3.  2.  4.  1.  0.5]
JC FIVE
  • 33
  • 5