Cube
Cube

Reputation: 23

Numpy slicing result different than for loop

I have some question regarding numpy/slicing in Python.

Can anyone explain, why the following for loop and the slicing approach don't result in the same B?

for n in range(1,N-1):
    B[n,i] = -(2*x[n,i] - x[n-1,i] - x[n+1,i])

B[1:N-2,i] = -(2*x[1:N-2,i] - x[0:N-3,i] - x[2:N-1,i])

Upvotes: 2

Views: 82

Answers (1)

aldanor
aldanor

Reputation: 3481

Because the ranges are non-inclusive on the right side, I assume you'd have to change your numpy code to

B[1:N-1,i] = -(2*x[1:N-1,i] - x[0:N-2,i] - x[2:N,i])

to make it match the loop version.

Upvotes: 2

Related Questions