0

I want to calculate euclidian distance matrix of (x,y,z) coordinates. I found the way of calculating euclidian distance matrix of (x,y) coordinates.

def euclidian_dist(x,y):
    diff = np.expand_dims(x, axis=1) - np.expand_dims(y, axis=0)
    distance_matrix = np.sqrt(np.sum(diff ** 2, axis=-1))
    return distance_matrix

if __name__=="__main__":
    #[[x1,y1],[x2,y2],...,[xn,yn]]
    p = np.array([[0.0, 0.0],[1., 0],[1, 1],[0, 1]])
    q = np.array([[0., 0],[1., 0],[0.3, 0.4],[0.7, 0.6]])
    euclidian_dist(p,q)

ans: array([[0.        , 1.        , 0.5       , 0.92195445],
            [1.        , 0.        , 0.80622577, 0.67082039],
            [1.41421356, 1.        , 0.92195445, 0.5       ],
            [1.        , 1.41421356, 0.67082039, 0.80622577]])

In the next step, I want to use x,y,z coordinates([[x1,y1,z1],[x2,y2,z2],...,[xn,yn,zn]])

and want to get euclidian distance matrix( shape:n✕n).

Could you let me know if you know the solution?

hpaulj
  • 221,503
  • 14
  • 230
  • 353
kkj
  • 81
  • 1
  • 8

1 Answers1

1

Use your same code for 3D points. It works fine:

def euclidian_dist(x,y):
    diff = np.expand_dims(x, axis=1) - np.expand_dims(y, axis=0)
    distance_matrix = np.sqrt(np.sum(diff ** 2, axis=-1))
    return distance_matrix

if __name__=="__main__":
    #[[x1,y1],[x2,y2],...,[xn,yn]]
    p = np.array([[0.0, 0.0, 0.0],[1.,1., 0],[1, 1, 1],[0, 0, 1]])
    q = np.array([[0., 0, 0],[1.,1., 0],[0.3,0.3, 0.4],[0.7, 0.6, 0.6]])
    print(euclidian_dist(p,q))

output:

[[0.         1.41421356 0.58309519 1.1       ]
 [1.41421356 0.         1.06770783 0.78102497]
 [1.73205081 1.         1.15758369 0.64031242]
 [1.         1.73205081 0.73484692 1.00498756]]
Ehsan
  • 12,072
  • 2
  • 20
  • 33