数组中所有点之间的最小欧几里得距离数组

array of minimum euclidian distances between all points in array

我有这个带有点的 numpy 数组,类似于

[(x1,y1), (x2,y2), (x3,y3), (x4,y4), (x5,y5)]

我想做的是获取所有最小距离的数组。 所以对于点 1 (x1, y1),我想要离它最近的点的距离,对于点 2 (x2,y2) 也是如此...... 距离为 sqrt((x1-x2)^2 + (y1-y2)^2).

这显然是一个与我的点数组长度相同的数组(在本例中:5 个点 -> 5 个最小距离)。

有没有不用循环的简洁方法?

此解决方案真正侧重于可读性而不是性能 - 它显式计算并存储整个 n x n 距离矩阵,因此不能被认为是有效的。

但是:非常简洁易读

import numpy as np
from scipy.spatial.distance import pdist, squareform

#create n x d matrix (n=observations, d=dimensions)
A = np.array([[1,9,2,4], [1,2,3,1]]).T

# explicitly calculate the whole n x n distance matrix
dist_mat = squareform(pdist(A, metric="euclidean"))

# mask the diagonal
np.fill_diagonal(dist_mat, np.nan)

# and calculate the minimum of each row (or column)
np.nanmin(dist_mat, axis=1)