简体   繁体   English

Numpy 以与滚动相反的顺序分度

[英]Numpy indexing in reverse order with roll

I have a 2d big matrix and I want to extrapolate submatrices from elements considering the first neighbours, with periodic boundaries .我有一个 2d 大矩阵,我想从考虑第一个邻居的元素中推断子矩阵,具有周期性边界 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 .但这仅适用于矩阵中间的每个 [x, y] ,但不适用于像 [0, 0] 这样的边界中的元素,其中像 [-1:2, -1:2] 这样的索引会给出一个空数组 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.我想我必须使用某种 2D np.roll但我不知道如何以干净有效的方式进行操作。 Thanks in advance!提前致谢!

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

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)通过在 numpy 中滚动 function 我找到了解决方案(滚动 +1-x、+1-y 的 arrays 并获得第一个 3x3 矩阵)

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM