Edition in order to simplify the question
I have two matrix :
- mat1 : nrow=100 000 ; ncol=5
- mat2 : nrow=500 000 ; ncol=5
Expected Results
Count the number of similar numbers between each row of mat1 with each row of mat2 :
Proposal
Intersection <- function(matrix1, matrix2){
Intersection = matrix(nrow=nrow(matrix1), ncol=ncol(matrix2))
for(i in 1:nrow(matrix3)) {
for(j in 1:ncol(matrix3)) {
Intersection[i,j] = length(intersect(matrix1[i,], matrix2[j,])
}
}
return(Intersection) }
Question:
How to vectorize this function in order to avoid loops ?
Data sample
Here is a sample of data in order to experiment a solution:
dput(matrix1) structure(c(1L, 20L, 2L, 1L, 7L, 2L, 22L, 12L, 2L, 27L, 3L, 35L, 16L, 3L, 32L, 4L, 37L, 35L, 17L, 33L, 5L, 38L, 46L, 27L, 49L), .Dim = c(5L, 5L))
dput(matrix2) structure(c(1, 14, 7, 1, 7, 2, 22, 12, 2, 27, 7, 35, 16, 3, 32, 14, 39, 35, 17, 32, 17, 38, 46, 20, 49), .Dim = c(5L, 5L))