[R] Multiplying a list of matrices with a vector

Mendolia, Franco fmendolia at mcw.edu
Thu Sep 29 00:04:57 CEST 2011


Hi all!

I have a list of matrices and I want to multiply the ith element of the list with the ith element of a another vector. That is,

> LL <- list(A=diag(3),B=diag(3),C=diag(3))
> vec <- 1:3
> for(i in 1:3)
+ {
+   LL[[i]] <- LL[[i]]*vec[i]
+ }
> LL
$A
     [,1] [,2] [,3]
[1,]    1    0    0
[2,]    0    1    0
[3,]    0    0    1

$B
     [,1] [,2] [,3]
[1,]    2    0    0
[2,]    0    2    0
[3,]    0    0    2

$C
     [,1] [,2] [,3]
[1,]    3    0    0
[2,]    0    3    0
[3,]    0    0    3

Is there another (more efficient) way of doing this without using loops? I found an older entry in this list with a similar problem, where the list elements were always multiplied with the same number, e.g., lapply(LL, function(x) x*3) and I was looking for something similar.

Best,
Franco


More information about the R-help mailing list