如果矩阵A和矩阵B之间的尺寸不等,如何计算R中的欧氏距离:
我有两个矩阵,即矩阵A和矩阵B
矩阵A:
[,1][,2]
[1,] 1 1
[2,] 1 2
[3,] 2 1
[4,] 2 2
[5,] 10 1
[6,] 10 2
[7,] 11 1
[8,] 11 2
[9,] 5 5
[10,] 5 6
矩阵B:
[,1][,2][,3][,4][,5][,6]
[1,] 2 1 5 5 10 1
[2,] 1 1 2 1 10 1
[3,] 5 5 5 6 11 2
[4,] 2 2 5 5 10 1
[5,] 2 1 5 6 5 5
[6,] 2 2 5 5 11 1
[7,] 2 1 5 5 10 1
[8,] 1 1 5 6 11 1
[9,] 2 1 5 5 10 1
[10,] 5 6 11 1 10 2
I want the Result matrix for List 1 to store result of
the euclidean distance between row 1 to row 10 in matrix A and every two
columns of row 1 in Matrix B as per below:
List [[1]]
[1,] [,2] [,3]
[1,] 1.00 5.66 9.00
[2,] 0.00 1.00 9.00
[3,] 5.66 6.40 10.05
[4,]
[5,]
[7,]
[8,]
[9,]
[10]
For List 2, I want the Result matrix to store the result of the euclidean
distance between row 1 to row 10 in matrix A and every two columns of row 2
in Matrix B as per below:
List [[2]]
[1,] [,2] [,3]
[1,] 1.41 5.00 9.06
[2,] 1.00 1.41 8.00
[3,]
[4,]
[5,]
[7,]
[8,]
[9,]
[10]
接下来,列表3用于Matrix B中的第3行
这应该继续到列表10
例如,要在结果矩阵列表1中获得以下答案:
[,1]
[1,] 1.00
计算结果如下:
A(1,1) - From Matrix A
B(2,1) - From Matrix B
= sqrt((xA -xB)^2 + (yA -yB)^2)
= sqrt((1-2)^2 + (1-1)^2)
= 1.00
xA and yA from Matrix A
xB and yB from Matrix B
获得以下答案:
[,2]
[1,] 5.66
计算结果如下:
A(1,1) - From Matrix A
B(5,5) - From Matrix B
= sqrt((xA -xB)^2 + (yA -yB)^2)
= sqrt((1-5)^2 + (1-5)^2)
= 5.66
获得以下答案:
[,3]
[1,] 9.00
计算结果如下:
A(1,1) - From Matrix A
B(10,1) - From Matrix B
= sqrt((xA -xB)^2 + (yA -yB)^2)
= sqrt((1-10)^2 + (1-1)^2)
= 9.00
这是我目前所拥有的,但它在Matrix A中的第一行之间进行计算 在矩阵B中使用第1行,依此类推。我想要的是矩阵A中的每一行在列表1中的矩阵B中的第一行,矩阵A中的每一行到矩阵B中的第二行,依此类推,直到矩阵B中的第10行;
ObjCentDist <- function(matrixA, matrixB) {
resultMatrix <- matrix(NA, nrow=dim(matrixA)[1],ncol=dim(matrixB[2]/2)
for(i in 1:nrow(matrixA)) {
for(j in 1:((dim(matrixB)[2])/2)) {
k = (j * 2) - 1
resultMatrix[i,j] <- sqrt(rowSums((t(matrixA[i,])matrixB[i,k:k+1)])^2))
}
}
resultMatrix
}
matrixA <- matrix(c(1,1,1,2,2,1,2,2,10,1,10,2,11,1,11,2,5,5,5,6), ncol = 2, byrow = TRUE)
matrixB <- matrix(c(2,1,5,5,10,1,1,1,2,1,10,1,5,5,5,6,11,2,2,2,5,5,10,1,2,1,5,6,5,5,2,2,5,5,11,1,2,1,5,5,10,1,1,1,5,6,11,1,2,1,5,5,10,1,5,6,11,1,10,2), nrow=10, ncol=6, byrow=TRUE)
我注意到了pdist()但是我不知道如何在循环中使用它并在mycase中获得所需的输出,因为我对R很新并且还在学习
答案 0 :(得分:2)
此解决方案需要2个不同的apply语句,因此从功能角度来看可能不是最好的,但它应该提供您想要的结果。 (编辑以简化代码)
# Get Euclidean distance from A to all pairs in B
alldist <- function(A, B) {
sapply(seq(2, length(B), by = 2), function(i) sqrt((A[,1] - B[i-1])^2 + (A[,2] - B[i])^2))
}
lapply(1:nrow(matrixB), function(n) alldist(A = matrixA, B = matrixB[n, ]))