简体   繁体   English

如何将函数应用于元素列表的矩阵

[英]How to apply a function to a list of matrices elementwise

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? 有没有人解决这个问题?

As docendo discimus suggested you can use mapply 正如docendo discimus建议您可以使用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

Map("*", l, v)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM