We have two matrices, for example:
A=
[,1] [,2] [,3]
[1,] -2 1 0
[2,] 1 0 -1
[3,] 0 -1 4
and
B=
[,1] [,2] [,3]
[1,] 1 2 3
[2,] 1 2 3
[3,] 3 1 2
[4,] 2 3 1
[5,] 3 1 2
I would to compute the distance matrix between the rows of A and B. In other words and using our example:
[,1] [,2] [,3]
[1,] dist(B[1,]-A[1,]) dist(B[1,]-A[2,]) dist(B[1,]-A[3,])
[2,] dist(B[2,]-A[1,]) dist(B[2,]-A[2,]) dist(B[2,]-A[3,])
[3,] dist(B[3,]-A[1,]) dist(B[3,]-A[2,]) dist(B[3,]-A[3,])
[4,] dist(B[4,]-A[1,]) dist(B[4,]-A[2,]) dist(B[4,]-A[3,])
[5,] dist(B[5,]-A[1,]) dist(B[5,]-A[2,]) dist(B[5,]-A[3,])
I was thinking of using the function "dist", that computes and returns the distance matrix of the distances between the rows of a data matrix. But it applies only to a single matrix. I have tried to use the command "rbind(A,B)" and to apply "dist" to the resulting matrix, but in this case I have obtained also the distances between the rows of same matrix.
Perhaps this way?
A = matrix(c(-2, 1, 0, 1, 0, -1, 0, -1, 4), ncol = 3, byrow = TRUE)
B = matrix(c(1, 2, 3, 1, 2, 3, 3, 1, 2, 2, 3, 1, 3, 1, 2), ncol = 3, byrow = TRUE)
t(sapply(1:nrow(B), function(x) {
sqrt(rowSums(t(t(A)-B[x,])^2))
}))
[,1] [,2] [,3]
[1,] 4.358899 4.472136 3.316625
[2,] 4.358899 4.472136 3.316625
[3,] 5.385165 3.741657 4.123106
[4,] 4.582576 3.741657 5.385165
[5,] 5.385165 3.741657 4.123106
# First build a matrix
Dist.M <- matrix(0, nrow = nrow(A), ncol = ncol(B))
# Complete the matrix
for (i in 1:nrow(A)){
for (j in 1:nrow(B)){
Dist.M[i,j] <- dist(rbind(A[i,],B[j,])
}
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.