两组不相等点之间的最小距离

2024-09-25 00:35:54 发布

您现在位置:Python中文网/ 问答频道 /正文

我想找出xy平面上两组点之间的最小距离。假设第一组点集合A有9个点,第二组点集合B有3个点。我想找出连接集合A中的每个点到集合B中的A点的最小总距离。显然会有一些重叠,甚至可能是集合B中一些没有连接的点。但是集合A中的所有点都必须有1个,并且只有1个链接从集合A指向集合B中的一个点

如果这两个问题的解的个数等于:

import random
import numpy as np
import matplotlib.pyplot as plt
from scipy.spatial.distance import cdist
from scipy.optimize import linear_sum_assignment

points1 = np.array([(x, y) for x in np.linspace(-1,1,3) \
          for y in np.linspace(-1,1,3)])
N = points1.shape[0]
points2 = 2*np.random.rand(N,2)-1

cost12 = cdist(points1, points2)
row_ind12, col_ind12 = linear_sum_assignment(cost12)

plt.plot(points1[:,0], points1[:,1], 'b*')
plt.plot(points2[:,0], points2[:,1], 'rh')
for i in range(N):
    plt.plot([points1[i,0], points2[col_ind12[i],0]], [points1[i,1], 
             points2[col_ind12[i],1]], 'k')
plt.show()


Tags: infromimport距离forplotasnp
1条回答
网友
1楼 · 发布于 2024-09-25 00:35:54

函数^{}执行您想要的操作。在

下面是您的代码的修改版本,它演示了vq

import numpy as np
from scipy.cluster.vq import vq
import matplotlib.pyplot as plt


# `points1` is the set A described in the question.
points1 = np.array([(x, y) for x in np.linspace(-1,1,3)
                               for y in np.linspace(-1,1,3)])

# `points2` is the set B.  In this example, there are 5 points in B.
N = 5
np.random.seed(1357924)
points2 = 2*np.random.rand(N, 2) - 1

# For each point in points1, find the closest point in points2:
code, dist = vq(points1, points2)


plt.plot(points1[:,0], points1[:,1], 'b*')
plt.plot(points2[:,0], points2[:,1], 'rh')

for i, j in enumerate(code):
    plt.plot([points1[i,0], points2[j,0]],
             [points1[i,1], points2[j,1]], 'k', alpha=0.4)

plt.grid(True, alpha=0.25)
plt.axis('equal')
plt.show()

脚本将生成以下绘图:

plot

相关问题 更多 >