[R] Vectorize a series of Matrix Multiplications

David Winsemius dwinsemius at comcast.net
Wed Jun 19 19:57:49 CEST 2013

On Jun 17, 2013, at 8:48 AM, G Vishwanath wrote:

> Can I have some help in vectorizing a series of matrix multiplications?
> Toy Example
> mat_size=2; num_matrices=3; num_users=2
> ToyArray=array(1,dim=c(mat_size,   mat_size, num_matrices, num_users))
> /* So I open an 4-dim array to store 3  2 X 2 matrrices  for 2 users.  For each user I want to multiple the 3, 2 X 2 matrices so that  at the end I have 1 matrix for each of the 2 users */
> This works:
>  output=array(NA,dim=c(mat_size, mat_size, num_users));
>  for ( i in 1:num_users) {
>   output[,,i]= as.matrix(ToyArray[,,1,i]) %*% as.matrix(ba[,,2,i]) %*% as.matrix(ba[,,3,i])
>  };

I'm pretty sure you can drop the as.matrix() calls since ToyArray[,,1,i] and ba[,,2,i] will be matrices. Look at the documentation for  ?"[" and pay attention to the "drop" argument (or look at ?drop since it is an R function). That should provide some increase in speed.

> ToyArray[,,1,2]
     [,1] [,2]
[1,]    1    1
[2,]    1    1

> Can I do better? Can I vectorize this over the user dimension?

I don't know. I would guess "not" since none of the help pages for array or ?matmult or the ones linking from it suggested that "%*%" should operate on arrays. (I would have tested my half-baked ideas if you had provided a reproducible example of 'ba'.)

> And even better (and a different question): what strategy can I use if the matrices are not all of the same  size?

This question is unclear to me. Sorry. It's lacking in details and example. (And I apologize if there is a duplicate of this that explains why smarter people than I have not already addressed it.)

David Winsemius
Alameda, CA, USA

More information about the R-help mailing list