Reputation: 101
I like to multiply all possible combinations of columns of two matrices that has same rows. Which means two matrices, e.g., a[3x3]
and b[3x4]
will generate 3x4 matrices with elements a[i,j]*a[k,j]
. (i
and k
represents rows ranging from 1 to 3 and j
represent column from 1 to 4)
I have created an example, that can do this job but was looking for elegant solution without for loop.
a <- matrix(1:12,3,4)
b <- matrix(1:9,3,3)
comb<-matrix(NA,3,(ncol(a)*ncol(b)))
for (i in 1:nrow(a)){
comb[i,]<-apply(expand.grid(a[i,],b[i,]),1,prod)
}
comb
Here a is 3x3 matrix, b is 3x4 matrix, and comb gives output of 3x12 matrix by multiplying various columns. I am looking for elegant solution that can be generalized to such multiplication to more than two matrices.
Upvotes: 3
Views: 1096
Reputation: 269431
Here are a few one-liners in decreasing order of length:
t(sapply(1:3, function(i) tcrossprod(a[i, ], b[i, ])))
t(mapply(outer, split(a, 1:3), split(b, 1:3)))
matrix(apply(a %o% b, c(2, 4), diag), 3)
(b %x% a)[!!diag(3), ]
Upvotes: 5