M-V
M-V

Reputation: 5237

Is there a Python slice notation equivalent for (i+1)%N?

I have a Python numpy array that I am using for a simulation with toroidal boundary conditions.

For example, at the boundary when i = N-1, i+1 becomes 0.

I am using a[(i+1)%N, (j+1)%N] for accessing nearest neighbors so the index automatically wraps around.

Just wondering if there's a faster way to do this, using the Python/Numpy slicing syntax.

Upvotes: 2

Views: 402

Answers (2)

JAB
JAB

Reputation: 21089

Take advantage of Python's negative indexing.

a[(i+1)-N, (j+1)-N]

is equivalent to your version using modulo. Proof:

>>> a = [1, 2, 3, 4, 5, 6, 7, 8, 9]
>>> for i in range(len(a)):
    print(a[(i+1)%len(a)], a[i+1-len(a)])


2 2
3 3
4 4
5 5
6 6
7 7
8 8
9 9
1 1

If the boundaries are smaller than the lengths of the axes of the array, you could take a slice of the array with the right boundaries (which shouldn't use too much memory in numpy, as it will just be a view into the original array) and then use the negative indexing method.

Upvotes: 1

Pablo
Pablo

Reputation: 2481

You could try with some similar to:

n = 10
a = range(n)
for i in range(n):
   print a[i-1],a[i],a[i-(n-1)]

I don't know the performance "+-" vs "%", but I believe that is faster than with %.

Upvotes: 0

Related Questions