Non-conformable matrix multiplication

No votes yet

This question hit the R-help mailing list:

"I'm having trouble using the 'apply' function to multiply some arrays. Let A be a 500x2 array and B a 500x3 array. I need a vector C which has 6 columns being the first three the result of A[,1] * B and the second three the result of A[,2] * B. What is the most efficient way to express that? I'm trying to use 'apply' with no success..."

As you can see, this isn't the job for * or %*% as both multiplications would result in a non-conformable array error; that is, with *, the matrices do not have the exact same dimensions, and, with %*%, the matrices do not have dimensions of the form i x k and k x j, to result in a i x j matrix.

My solution, using apply, as suggested in the question, was to the following:

a <- matrix(cbind(rep(2, 500), rep(3, 500)), 500, 2)
b <- matrix(cbind(rep(5, 500), rep(6, 500), rep(7, 500)), 500, 3)

matrix(apply(a, c(2), "*", b), nrow=500, ncol=6)

We apply the multiplier, * (quoted as specified in the apply help), with argument b to every column of a (specified by c(2)), then reformat the results using the matrix function into a 500x6 matrix as desired.