Efficiently Calculating a Euclidean Distance Matrix Using Numpy

后端 未结 4 483
我在风中等你
我在风中等你 2020-11-30 02:31

I have a set of points in 2-dimensional space and need to calculate the distance from each point to each other point.

I have a relatively small number of points, ma

4条回答
  •  自闭症患者
    2020-11-30 03:13

    Here is how you can do it using numpy:

    import numpy as np
    
    x = np.array([0,1,2])
    y = np.array([2,4,6])
    
    # take advantage of broadcasting, to make a 2dim array of diffs
    dx = x[..., np.newaxis] - x[np.newaxis, ...]
    dy = y[..., np.newaxis] - y[np.newaxis, ...]
    dx
    => array([[ 0, -1, -2],
              [ 1,  0, -1],
              [ 2,  1,  0]])
    
    # stack in one array, to speed up calculations
    d = np.array([dx,dy])
    d.shape
    => (2, 3, 3)
    

    Now all is left is computing the L2-norm along the 0-axis (as discussed here):

    (d**2).sum(axis=0)**0.5
    => array([[ 0.        ,  2.23606798,  4.47213595],
              [ 2.23606798,  0.        ,  2.23606798],
              [ 4.47213595,  2.23606798,  0.        ]])
    

提交回复
热议问题