Iterating With Numpy With Different Indexes
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"