Python 快速计算两个三维点阵列之间最小距离的方法

Python 快速计算两个三维点阵列之间最小距离的方法,python,arrays,numpy,distance,Python,Arrays,Numpy,Distance,我想知道是否有一种快速的方法来计算三维numpy阵列的所有点(a[N,3])到第二个三维numpy阵列的所有点(B[M,3])之间的欧几里德距离 然后,我应该得到一个数组C,它将是[N,M],具有从数组A点到数组B点的所有距离,然后沿指定轴使用np.min()来获得从集合A点到集合B点的所有最小距离 到目前为止,我就是这样实施的: distances = np.repeat(9999, len(A)) for i, point in enumerate(A): min_distance =

我想知道是否有一种快速的方法来计算三维numpy阵列的所有点(
a[N,3]
)到第二个三维numpy阵列的所有点(
B[M,3]
)之间的欧几里德距离

然后,我应该得到一个数组
C
,它将是
[N,M]
,具有从数组
A
点到数组
B
点的所有距离,然后沿指定轴使用
np.min()
来获得从集合
A
点到集合
B
点的所有最小距离

到目前为止,我就是这样实施的:

distances = np.repeat(9999, len(A))
for i, point in enumerate(A):
  min_distance = np.min(np.sqrt(np.sum(np.square(point - B), axis=1)))
  distances[i] = min_distance
有没有办法摆脱for循环


提前感谢:)

如果scipy方法不起作用,或者您确实有其他原因,这里有一个简单的方法-

将numpy导入为np
x=np.random.random((200,3))
y=np.随机.随机((100,3))
x=x.重塑(-1,1,3))#[200x1x3]
y=np.展开尺寸(y,轴=0)#[1x100x3]
y=y.重复(x.形状[0],轴=0)#[200x100x3]
距离=np.linalg.norm(y-x,轴=2)#差值为[200x100x3],norm结果为[200x100]

来自scipy.spatical import distance\u矩阵;dist_mat=distance_matrix(A,B)
。虽然这段代码可以回答这个问题,但最好包含一些上下文,解释它是如何工作的以及何时使用它。从长远来看,只使用代码的答案是没有用的。
import numpy as np

# arrays with xyz coordinates of all points 
a = np.asarray([[xa1,ya1,za1],...,[xan,yan,zan]])
b = np.asarray([[xb1,yb1,zb1],...,[xbn,ybn,zbn]])

# reshaping to be able to calculate the distance matrix
a_reshaped = a.reshape(a.shape[0], 1, 3)
b_reshaped = b.reshape(1, b.shape[0], 3)

"""calculation of all distances between all points  - creates a 
len(a) x len(b) matrix""" 
distance = np.sqrt(np.sum((a_reshaped - b_reshaped)**2, axis=2))