I am trying to make some piece of code more efficient by using the vectorized form in numpy. Let me show you an example so you know what I mean.
Given the following code:
a = np.zeros([4,4])
a[0] = [1., 2., 3., 4.]
for i in range(len(a)-1):
a[i+1] = 2*a[i]
print a
It outputs
[[ 1. 2. 3. 4.]
[ 2. 4. 6. 8.]
[ 4. 8. 12. 16.]
[ 8. 16. 24. 32.]]
When I now try to vectorize the code like this:
a = np.zeros([4,4])
a[0] = [1., 2., 3., 4.]
a[1:] = 2*a[0:-1]
print a
I just get the first iteration correct:
[[ 1. 2. 3. 4.]
[ 2. 4. 6. 8.]
[ 0. 0. 0. 0.]
[ 0. 0. 0. 0.]]
Is it possible to write the code above efficiently in a vectorized form (where the next iteration always accesses the previous iteration) or do I have to keep the for
loop?