Home > Back-end >  Numpy indexing in reverse order with roll
Numpy indexing in reverse order with roll

Time:01-27

I have a 2d big matrix and I want to extrapolate submatrices from elements considering the first neighbours, with periodic boundaries. I did something like this:

neighborhood = big_matrix[x-1:x 2, y-1:y 2]

but this only works for every [x, y] in the middle of the matrix but not for elements in the borders like [0, 0] where indexing like [-1:2, -1:2] gives an empty array. I think I have to use some sort of 2D np.roll but I don't know how to do it in a clean and efficient way. Thanks in advance!

CodePudding user response:

Not sure if it is the solution you are looking for:

import numpy as np

x=0
y=0

big_matrix = np.random.randint(5, size=(10,10))
print(big_matrix)
#new_matrix = big_matrix[x-1 :x 2, y-1:y 2]
new_matrix = big_matrix[x if x==0 else x-1 :x 2, y if y==0 else y-1:y 2]
new_matrix

CodePudding user response:

By playing with the roll function in numpy I found the solution (roll the arrays of 1-x, 1-y and get the first 3x3 matrix)

np.roll(big_matrix, (1-x, 1-y), axis=(0, 1))[:3, :3]
  •  Tags:  
  • Related