1
votes

Let say we have two matrices, i.e. M1 and M2, of dimensions n1 x m and n2 x m, respectively.

How we can find which rows of M1 are identity to those of M2 (and exceptional vice versa) ?

The preferable output is a matrix, whose the number of rows is equal to the identity rows between the matrices M1 and M2, and two columns, that is, the first column will contain the number of row of matrix M1 and the second one the number of row of matrix M2.

2

2 Answers

1
votes

There might be a slicker way, but this seems to work...

#dummy data
M1 <- matrix(1:8,ncol=2)
M2 <- matrix(c(1,3,4,5,6,8),ncol=2)

M1
     [,1] [,2]
[1,]    1    5
[2,]    2    6
[3,]    3    7
[4,]    4    8

M2
     [,1] [,2]
[1,]    1    5
[2,]    3    6
[3,]    4    8

which(apply(M2, 1, function(v) 
           apply(M1, 1, function(w) sum(abs(w-v))))==0,
      arr.ind = TRUE)

     row col
[1,]   1   1
[2,]   4   3

The row column is the row index of M1, the col column is the index of matching rows in M2.

1
votes

Create example matrices with 4 matching rows

set.seed(0)
M1 <- matrix(runif(100), 10)
M2 <- rbind(M1[sample(10, 4),], matrix(runif(60), 6))

Create output

splits <- lapply(list(M1, M2), function(x) split(x, row(x)))
out <- cbind(M1 = seq(nrow(M1)), M2 = do.call(match, splits))
out[!is.na(out[,2]),]
#      M1 M2
# [1,]  2  4
# [2,]  3  3
# [3,]  6  2
# [4,]  7  1