Skip to content Skip to sidebar Skip to footer

Iterating With Numpy With Different Indexes

Say I have a for loop using range as shown below. Is there a good way to eliminate the for loop and use numpy arrays only? y =[146, 96, 59, 133, 192, 127, 79, 186, 272, 155, 98, 21

Solution 1:

You asked something similar in Iterating over a numpy array with enumerate like function, except there A and B did not change.

Strictly speaking you can't vectorize this case, because of that change in Bt. This an iterative problem, where the i+1 term depends on the i term. Most of the numpy vector operations operate (effectively) on all terms at once.

Could you rework the problem so it makes use of cumsum and/or cumprod? Those are builtin methods that step through a vector (or axis of an array), calculating a cumulative sum or product. numpy's generalization of this is ufunc.accumulate. http://docs.scipy.org/doc/numpy/reference/generated/numpy.ufunc.accumulate.html

In the meantime, I'd suggest making more use of arrays

y = np.array(y)
At = np.zeros(y.shape)
Bt = np.zeros(y.shape)
At[0] = 3
Bt[0] = 2 
for i in range(len(y)-1):
    A, B = At[i],Bt[i]
    At[i+1] =y[i] / y[i] + 5 * (A + B)
    Bt[i+1] =(At[i+1] - A) + y[i+1] * B

numpy uses an nditer to step through several array (including an output one) together. http://docs.scipy.org/doc/numpy/reference/arrays.nditer.html Though I suspect it is more useful when working on multidimensional arrays. For your 1d arrays it is probably overkill. Still if speed becomes essential, you could work through this documentation, and implement the problem in cython.

Post a Comment for "Iterating With Numpy With Different Indexes"