Reputation: 458
I have a list of matrices and I would like to multiply each matrix with a different factor from a vector of the same length as the list. I tried the following:
lapply(list(mat1, mat2, mat3),"*",c(1,2,3))
However, this returns:
list(mat1*c(1,2,3), mat2*c(1,2,3), mat3*c(1,2,3))
instead of what I need:
list(mat1*1,mat2*2,mat3*3)
Has anybody a solution to this problem?
Upvotes: 1
Views: 1019
Reputation: 9628
As docendo discimus suggested you can use mapply
l <- list(matrix(1:4, ncol = 2), matrix(5:8, ncol = 2), matrix(9:12, ncol = 2))
v <- 1:3
mapply(function(x,y) x*y, x = l, y = v, SIMPLIFY = FALSE)
Or just use Map
Map("*", l, v)
Upvotes: 5