[英]Fast way to calculate min distance between two numpy arrays of 3D points
我想知道是否有一種快速方法可以計算 3D numpy 數組( A [N,3]
)的所有點與第二個 3D 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 方法-
import numpy as np
x = np.random.random((200, 3))
y = np.random.random((100,3))
x = x.reshape((-1, 1, 3)) # [200x1x3]
y = np.expand_dims(y, axis=0) # [1x100x3]
y = y.repeat(x.shape[0], axis=0) # [200x100x3]
distance = np.linalg.norm(y-x, axis=2) # Difference is [200x100x3] and norm results in [200x100]
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))
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.