简体   繁体   中英

Fastest way in numpy to get distance of n pairs

I have n pairs of vectors with m dimensions. I want to find the fastest way to calculate the eculidian distance of these n pairs. One way is to iterate over each pair and calculate the distance between the vectors.

If I understand your question, you have two arrays of coordinates and you want the element-wise euclidean distance. If so, see the following example

>>> import numpy as np
>>> a = np.array([[1,2], [3,4], [5,6], [7,8]])
>>> b = np.array([[2,4], [1,1], [8,9], [1,2]])

You can use numpy.linalg.norm along with the axis argument to compute an element-wise euclidean distance

>>> np.linalg.norm(a - b, axis=1)
array([2.23606798, 3.60555128, 4.24264069, 8.48528137])

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM