python - 如何用矢量化计算距离矩阵的种类

标签 python numpy vectorization

我有一个形状为 4 X 3 X 2 的 numpy 数组 A。下面的每一行都是一个节点的二维坐标。 (在我的有限元分析中,每三个节点组成一个三角形。)

array([[[0., 2.],  #node00 
        [2., 2.],  #node01
        [1., 1.]], #node02

       [[0., 2.],  #node10
        [1., 1.],  #node11
        [0., 0.]], #node12

       [[2., 2.],  #node20
        [1., 1.],  #node21
        [2., 0.]], #node22

       [[0., 0.], #node30
        [1., 1.], #node31
        [2., 0.]]]) #node32

我有另一个 numpy 数组 B 预先计算的“中心”的坐标:

array([[1.        , 1.66666667], # center0
       [0.33333333, 1.        ], # center1
       [1.66666667, 1.        ], # center2
       [1.        , 0.33333333]])# center3

我怎样才能像这样有效地计算欧几里德距离的矩阵 C

dist(center0, node00) dist(center0,node01) dist(center0, node02)
dist(center1, node10) dist(center1,node11) dist(center1, node12)
dist(center2, node20) dist(center2,node21) dist(center2, node22)
dist(center3, node30) dist(center3,node31) dist(center3, node32)

其中 dist 表示欧几里得距离公式,如 math.dist 或 numpy.linalg.norm?即结果矩阵的i,j元素为中心i到节点ij的距离。

需要矢量化代码而不是循环,因为我的实际数据来自非常大的医学成像。使用嵌套循环,可以获得如下预期输出:

In [63]: for i in range(4):
    ...:     for j in range(3):
    ...:         C[i,j]=math.dist(A[i,j], B[i]) 

In [67]: C
Out[67]:
array([[1.05409255, 1.05409255, 0.66666667],
       [1.05409255, 0.66666667, 1.05409255],
       [1.05409255, 0.66666667, 1.05409255],
       [1.05409255, 0.66666667, 1.05409255]])

[编辑] 这是与 Pairwise operations (distance) on two lists in numpy 不同的问题,因为需要在此处妥善解决诸如索引之类的问题。

最佳答案

a = np.reshape(A, [12, 2])
b = B[np.repeat(np.arange(4), 3)]
c = np.reshape(np.linalg.norm(a - b, axis=-1), (4, 3))
c
# array([[1.05409255, 1.05409255, 0.66666667],
#        [1.05409255, 0.66666667, 1.05409255],
#        [1.05409255, 0.66666667, 1.05409255],
#        [1.05409255, 0.66666667, 1.05409255]])

关于python - 如何用矢量化计算距离矩阵的种类,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/73405701/

相关文章:

python - 如何在 Linux 下读取 GPS 数据?

python - 将组中项目的长度/数量分配给新列

python - 根据连续行的空条件合并任意数量的文本列

python - matplotlib 图形只显示点而不是线

python - 将二维数组乘以一维数组

python - 为什么要在 Django url 末尾使用额外的斜杠 (/)?

python - 将数组转换为 Pandas 数据框列

python - 用于大型多光谱图像的 Numpy 计算 corrcoef

r - 从数据帧的第 n 列中获取值,每行 n 不同

octave - 在 Octave 中迭代矩阵行而不使用索引或 for 循环