问题
If I have two single-dimensional arrays of length M and N what is the most efficient way to calculate the euclidean distance between all points with the resultant being an NxM array? I'm trying to figure this out with Numpy but am pretty new to it so I'm a little stuck.
Currently I am doing it this way:
def get_distances(x,y):
#compute distances between all points
distances = np.zeros((len(y),len(x)))
for i in range(len(y)):
for j in range(len(x)):
distances[i,j] = (x[j] - y[i])**2
return distances
回答1:
Suppose you have 1-dimensional positions :
a = np.random.uniform(50,200,5)
b = np.random.uniform(50,200,3)
you can just use broadcasting:
result = np.abs(a[:, None] - b[None, :])
with the result being:
array([[ 44.37361012, 22.20152487, 89.04608885],
[ 42.83825434, 20.66616909, 87.51073307],
[ 0.19806059, 21.97402467, 44.87053932],
[ 8.42276237, 13.74932288, 53.0952411 ],
[ 8.12181467, 30.29389993, 36.55066406]])
So the i, j index is the distance between point i from array 1 and point j of array 2
if you want the result to be NxM in shape you need to exchange a
and b
:
result = np.abs(b[:, None] - a[None, :])
来源:https://stackoverflow.com/questions/35806681/euclidean-distance-between-all-points-in-an-2-vectors