Python Forum
euclidean distance - Printable Version

+- Python Forum (https://python-forum.io)
+-- Forum: Python Coding (https://python-forum.io/forum-7.html)
+--- Forum: General Coding Help (https://python-forum.io/forum-8.html)
+--- Thread: euclidean distance (/thread-17115.html)



euclidean distance - jenya56 - Mar-29-2019

Dear all,
I have two 2D arrays (size nxm) and I want to calculate the Euclidean distance between them. Meaning that the distance will be a single number whereas my arrays are nxm.
Is there a quick way to do it besides going into double loop?
Thank you!
Jenya


RE: euclidean distance - scidam - Mar-29-2019

You can use SciPy library, look at cdist function.


RE: euclidean distance - jenya56 - Mar-29-2019

Does cdist return a single number? Because I thought it would return a matrix? Thank you!


RE: euclidean distance - scidam - Mar-29-2019

Yes, it returns a matrix. Look at the following minimal example:

from scipy.spatial.distance import cdist
import numpy as np
np.random.seed(10)
X = np.random.rand(3, 10)
Y = np.random.rand(4, 10)
cdist(X, Y)
Output:
array([[1.00025041, 1.11616128, 1.49867252, 1.33747696], [1.76040012, 1.26928995, 1.4958863 , 1.31219674], [1.21858991, 1.08164983, 1.0274891 , 1.11686588]])