【问题标题】:array of minimum euclidian distances between all points in array数组中所有点之间的最小欧几里得距离数组
【发布时间】:2015-06-11 16:48:13
【问题描述】:

我有这个带有点的 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 个最小距离)。

有什么简洁的方法可以在不使用循环的情况下做到这一点?

【问题讨论】:

标签: python numpy scipy distance


【解决方案1】:

这个解决方案真正关注的是可读性而不是性能 - 它显式计算和存储整个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)

【讨论】:

    猜你喜欢
    • 2021-01-30
    • 2016-02-15
    • 2013-02-12
    • 1970-01-01
    • 1970-01-01
    • 2021-01-08
    • 2011-01-29
    • 2013-10-17
    • 2019-02-24
    相关资源
    最近更新 更多