当给定n维矩阵和1的网格大小时,我想计算一个字段的最近邻居.下面给出的是二维场的示例
P = (1,1)
p_neighbours = [(0,0),(2,2),(0,1),(0,2),(1,0),(2,0),(2,1),(1,2)]
Run Code Online (Sandbox Code Playgroud)
在数学上,这可以像矢量系统中的P +/- 1一样容易描述(据我所知).n维相邻数组的大小被描述为(n ^ 3)-1我已经找到了一个相当不错的老话题,无论如何我无法理解如何将任何呈现的解决方案扩展到n维功能..
from itertools import product
def stencil(dim):
stencils = list(product([-1,0,1], repeat=dim))
zero = ((0,) * dim)
stencils.remove(zero)
return stencils
def neighbours(P):
stencils = stencil(len(P))
return [tuple([sum(x) for x in zip(P,s)]) for s in stencils]
P = (4, 4, 4)
print(neighbours(P))
Run Code Online (Sandbox Code Playgroud)