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

Python 两组不相等的点之间的最小距离,python,numpy,scipy,pdist,Python,Numpy,Scipy,Pdist,我希望能够找到xy平面上两组点之间的最小距离。让我们假设第一组点集合A有9个点,第二组点集合B有3个点。我想找出集合A中的每个点与集合B中的A点之间的最小总距离。显然会有一些重叠,甚至集合B中的一些点没有链接。但是集合A中的所有点都必须有1个且只有1个链接从它到集合B中的点 如果两个集合的点数相等,我已经找到了这个问题的解决方案,下面是代码: import random import numpy as np import matplotlib.pyplot as plt from scipy.s

我希望能够找到xy平面上两组点之间的最小距离。让我们假设第一组点集合A有9个点,第二组点集合B有3个点。我想找出集合A中的每个点与集合B中的A点之间的最小总距离。显然会有一些重叠,甚至集合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()

该函数可执行您想要的操作

下面是代码的修改版本,演示了
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()
该脚本生成以下绘图:


您只是想在B中找到每个A点的最近邻吗?您能发布绘图或其他代码输出吗?我发布了绘图。是的,我正在努力寻找A最近的B邻居。