Reputation: 6777
I am trying to write a code that given a position (x,y) of a matrix of integers, I could iterate around all neighbors (left, right, up, down and diagonals) of distance K, this way:
K = 1
01 02 03 04 05 06
07 08 09 10 11 12
13 14 15 16 17 18
19 20 21 22 23 24
25 26 27 28 29 30
for i in range(M):
for j in range(N):
for ... #loop that i am writing... <br/>
#for (0,0) is [(0,0), (0,1), (1,0), (1, 1)]
#for (3, 3) is [(2,2), (2,3), (2,4), (3,2), (3,3), (3,4), (4,2), (4,3), (4,4)
This way for all positions in matrix.
Any tip or code?
Upvotes: 1
Views: 108
Reputation: 363233
Numpy slicing will make this pretty easy
>>> import numpy as np
>>> a = np.array(range(25)).reshape((5,5))
>>> print a
[[ 0 1 2 3 4]
[ 5 6 7 8 9]
[10 11 12 13 14]
[15 16 17 18 19]
[20 21 22 23 24]]
>>> k = 1
>>> a[2, 3]
13
>>> a[2-k:2+k+1, 3-k:3+k+1]
array([[ 7, 8, 9],
[12, 13, 14],
[17, 18, 19]])
Be careful of edge-cases, where index -1 will wrap to the other side of the array.
Upvotes: 1