[英]How to calculate the euclidean distance in R between two matrices each with unequal dimensions
[英]how to calculate Euclidean distance between two matrices in R
我有兩個尺寸相等的巨大矩陣。 我想計算它們之間的歐幾里得距離。 我知道這是 function:
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 的每對值之間的歐幾里得距離。
請問有什么建議嗎?
您可以使用包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)
這是基本函數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
通過使用tcrossprod
outer
組合,您可以在基礎 R 中比使用pdist::pdist
稍微快一點:
> library(Rfast);library(pdist);library(microbenchmark)
> mat1=matrix(sample(1e4),ncol=10);mat2=matrix(sample(2e4),ncol=10)
> microbenchmark(times=10,dista={Rfast::dista(mat1,mat2)},
+ tcrossprod={sqrt(outer(rowSums(mat1^2),rowSums(mat2^2),"+")-tcrossprod(mat1,2*mat2))},
+ pdist=pdist::pdist(mat1,mat2))
Unit: milliseconds
expr min lq mean median uq max neval
dista 36.54904 36.92631 41.87249 40.65317 44.69080 55.03735 10
tcrossprod 27.93673 31.27754 37.89734 36.94241 42.85898 52.00793 10
pdist 37.83836 39.03578 43.54179 44.04779 46.86191 50.45233 10
或者這不是 OP 所要求的,但是如果您有兩個具有相同維度的矩陣,它會創建一個矩陣的第一行、矩陣的第二行之間的距離向量,依此類推:
sapply(rowSums((mat1-mat2)^2),sqrt)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.