how to calculate Euclidean distance between two matrices in R

后端 未结 2 1637
执念已碎
执念已碎 2021-01-05 13:10

I have two huge matrices with equal dimensions. I want to calculate Euclidean distance between them. I know this is the function:

euclidean_distance <- fu         


        
相关标签:
2条回答
  • 2021-01-05 13:43

    This is a job for the base function outer:

    outer(mat1,mat2,Vectorize(euclidean_distance))
    
             x         y         z
    x  9220.40  9260.736  8866.034
    y 12806.35 12820.086 12121.927
    z 11630.86 11665.869 11155.823
    
    0 讨论(0)
  • 2021-01-05 14:07

    You can use the package pdist:

    library(pdist)
    dists <- pdist(t(mat1), t(mat2))
    as.matrix(dists)
             [,1]      [,2]      [,3]
    [1,]  9220.40  9260.735  8866.033
    [2,] 12806.35 12820.086 12121.927
    [3,] 11630.86 11665.869 11155.823
    

    this will give you all Euclidean distances of the pairs: (mat1$x,mat2$x), (mat1$x,mat2$y),..., (mat1$z,mat2$z)

    0 讨论(0)
提交回复
热议问题