如何计算R中两个矩阵之间的欧氏距离

时间:2016-01-30 20:10:25

标签: r

我有两个尺寸相同的巨大矩阵。我想计算它们之间的欧几里德距离。我知道这是功能:

euclidean_distance <- function(p,q){
  sqrt(sum((p - q)^2))
}

and if these are two matrices:


set.seed(123)
    mat1 <- data.frame(x=sample(1:10000,3), 
                       y=sample(1:10000,3), 
                       z=sample(1:10000,3))
    mat2 <- data.frame(x=sample(1:100,3), 
                       y=sample(1:100,3), 
                       z=sample(1:1000,3))

然后我需要答案是一个新的矩阵3 * 3,显示mat1和mat2的每对值之间的欧几里德距离。

有什么建议吗?

2 个答案:

答案 0 :(得分:7)

这是基函数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

答案 1 :(得分:5)

您可以使用包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

这将为您提供所有欧几里德距离:(mat1 $ x,mat2 $ x),(mat1 $ x,mat2 $ y),...,(mat1 $ z,mat2 $ z)