Home > OS >  vectorize recursive function of numpy array where each element depend on all of the previous ones
vectorize recursive function of numpy array where each element depend on all of the previous ones

Time:09-24

Be a an ndarray, e. g.:

a = np.random.randn(Size)

Where Size >> 1. Is it possible to define an array b s.t. its i-th element depends on all of the elements of a up to i (excluded or included is not the problem) without a for loop?

b[i] = function(a[:i])

So if function was simply np.sum(a[:i]) my desired output would be:

for i in range(1, Size):
    b[i] = np.sum(a[:i])

The only solution I was able to think about was to write the corresponding C code and wrap it, but is there some python native solution to avoid it???

I stress that the sum is a mere ex., I'm lookin for a generalization to arbitrary function that can, howewver, be expressed elementwise by means of numpy mathematical function (np.exp() e.g.)

CodePudding user response:

Many of the ufunc have an accumulate method. np.cumsum is basically np.add.accumulate. But if you can't use one of those, or some clever combination, and you still want speed, you will need to write some sort of compiled code. numba seems to be preferred tool these days.

CodePudding user response:

In your example use just numpy cumsum operation https://numpy.org/doc/stable/reference/generated/numpy.cumsum.html.

Edit:

For example, if you create a = np.ones(10) with all values equal 1. Then b = np.cumsum(a) will contain [1 2 ... 10].

Or as you wanted:

for i in range(1, Size):
    b[i] = np.sum(a[:i])

Also you can specify axis to apply cumsum to or maybe use numpy.cumprod (same operation but with product).

  • Related