我有两个尺寸相同的巨大矩阵.我想计算它们之间的欧几里德距离.我知道这是功能:
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))
Run Code Online (Sandbox Code Playgroud)
然后我需要答案是一个新的矩阵3*3,显示mat1和mat2的每对值之间的欧几里德距离.
有什么建议吗?
这是基本功能的工作outer:
outer(mat1,mat2,Vectorize(euclidean_distance))
Run Code Online (Sandbox Code Playgroud)
x y z
x 9220.40 9260.736 8866.034
y 12806.35 12820.086 12121.927
z 11630.86 11665.869 11155.823
你可以使用这个包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
Run Code Online (Sandbox Code Playgroud)
这将给你所有欧几里德距离的对:(mat1 $ x,mat2 $ x),(mat1 $ x,mat2 $ y),...,(mat1 $ z,mat2 $ z)
| 归档时间: |
|
| 查看次数: |
7739 次 |
| 最近记录: |