1

I have a function f which I am using to evolve a Numpy array z repeatedly. Thus my code looks like this:

for t in range(100):
    z = f(z)

However, now I want to combine elements of array while evolving. For example, in simple Python, I would like to do something like this:

N = len(z)
for t in range(100):
    for i in range(len(z)):
         z_new[i] = f(z[i]) + z[(i-1)%N] + z[(i+1)%N]
    z = z_new

How can achieve the same thing in Numpy vector operations so that I wouldn't have to compromise with the great speed that Numpy gives me?

Thanks in advance

4
  • When i is the index of the last element, what will z[i+1] be? Commented Jun 19, 2015 at 7:03
  • I actually use modulo. So the actual entries are z[(i-1)%N] and z[(i+1)%N] so that z[i+1] = z[0] when i is last element. Also, here N = len(z). Commented Jun 19, 2015 at 7:05
  • Slices are the fastest way to index your array, eg z[1:]-z[:-1]. If you have to wrap around you will have to use slower advanced indexing or concatenation. Look at the internals of roll. Look also at take and put. Commented Jun 19, 2015 at 8:49
  • Add the wrapping reqirement to your iterative example. Commented Jun 19, 2015 at 8:51

1 Answer 1

2

You can roll the data back and forth to achieve the same result.

Z = f(z)
Z = np.roll(Z, 1) + z
Z = np.roll(Z, -2) + z
z = np.roll(Z, 1)

I had also first thought about slicing but went with np.roll when I found it.

Prompted by @hpaulj's comment I came up with a slice solution:

q = np.array([1,2,3,4,5])
Q = f(q)
# operate on the middle
Q[1:] += q[:-1]
Q[:-1] += q[1:]
# operate on the ends
Q[0] += q[-1]
Q[-1] += q[0]

q = Q.copy()
Sign up to request clarification or add additional context in comments.

1 Comment

Actually my real task is much more complicated but I think this wonderful roll function should do the job. Thanks

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.