我有一个由dim q(行)p(列)组成的二维网格。网格的元素是元素本身的索引。所以元素ai,j=(i,j)。
现在我需要在这些点之间创建具有圆度约束的成对距离,这意味着元素距离(ai,p-1,ai,0)=1 (我使用的是基于0索引的矩阵,就像在Python中一样)。类比距离(aq-1,j,a0,j)=1
注意到distance(aq-2,j,a0,j)是从0到q-2的较短的垂直路径,以及从q2到0的路径(利用网格的圆度)。同样的事情在水平方向上也会发生。
我的问题是:有没有一个NumPy函数可以快速计算这样的成对距离矩阵?
发布于 2021-05-12 03:51:23
我不知道有哪个函数可以做到这一点,但它很容易手动计算:
import numpy as np
q = 6 # rows
p = 5 # columns
# Create array of indices
a = np.mgrid[0:q, 0:p].transpose(1, 2, 0)
# The array `a` now has shape (q, p, 2) :
a[1, 2] # array([1, 2])
a[3, 0] # array([3, 0])
# Create a new array measuring the i,j difference between all pairs of
# locations in the array. `diff` will have shape (q, p, q, p, 2) :
diff = a[None, None, :, :, :] - a[:, :, None, None, :]
# Modify diff to obey circularity constraint
di = diff[..., 0]
dj = diff[..., 1]
di[di > q//2] -= q
dj[dj > p//2] -= p
# compute distance from diff
dist = (diff[..., 0]**2 + diff[..., 1]**2)**0.5
# test:
dist[1, 0, 1, 0] # 0.0
dist[1, 0, 1, 1] # 1.0
dist[1, 0, 1, 2] # 2.0
dist[1, 0, 1, 3] # 2.0
dist[1, 0, 1, 4] # 1.0https://stackoverflow.com/questions/67492686
复制相似问题