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.