Search code examples
rmatrixapplysapply

Multiply two matrices with different dimensions in R


I am trying to use (s)apply to multiply two matrices with different dimensions. The matrices are:

xx <- matrix(c(1, 2, 3, 4, 5, 6), nrow=2, ncol=3, byrow=T)
yy <- matrix(c(10, 100), nrow=2, ncol=1, byrow=T)

What I want is to multiply each row of one matrix for each row of the other matrix and obtain this:

> zz
      [,1]  [,2]  [,3]
[1,]    10    20    30
[2,]   400   500   600

I have tried sapply(yy, function(x) xx*x) which produces a 6x2 matrix instead of the 3x2 matrix I want. Also apply(yy, 2, function(x) xx*x) which produces a 6x1 matrix does not work. In a similar situation in the past I used sapply without problem so I do not understand why this is not working now (I always had a bit of trouble in wrapping my head around *apply). What am I doing wrong?


Solution

  • Convert yy to a vector by c() and it will be recycled to the dimension of xx when multiplying.

    xx * c(yy)
    
    #      [,1] [,2] [,3]
    # [1,]   10   20   30
    # [2,]  400  500  600
    

    Or by matrix multiplication :

    diag(c(yy)) %*% xx