我希望能够找到 xy 平面中两组点之间的最小距离。假设第一组点集 A 有 9 个点,第二组点集 B 有 3 个点。我想找到将集合 A 中的每个点连接到集合 B 中的点的最小总距离。显然会有一些重叠,甚至可能集合 B 中的一些点没有链接。但是集合 A 中的所有点都必须有 1 个并且只有 1 个链接从它到集合 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()