将R列表(矩阵)的每个成员相互相乘

时间:2021-05-07 11:59:52

I have a list of equally sized matrices in R that I want to multiply by each other.

我在R中有一个相同大小的矩阵列表,我希望彼此相乘。

I am looking for a way to do:

我正在寻找一种方法:

list$A * list$B * list$C * ...

Without having to type it out by hand (my list has dozens of matrices).

无需手动输入(我的列表有几十个矩阵)。

1 个解决方案

#1


13  

Use Reduce if you want an element-by-element multiplication

如果需要逐个元素乘法,请使用Reduce

> Lists <- list(matrix(1:4, 2), matrix(5:8, 2), matrix(10:13, 2))
> Reduce("*", Lists)
     [,1] [,2]
[1,]   50  252
[2,]  132  416

Instead of using abind you can use simplify2array function and apply

您可以使用simplify2array函数并应用而不是使用abind

> apply(simplify2array(Lists), c(1,2), prod)
     [,1] [,2]
[1,]   50  252
[2,]  132  416

If you want to use abind then use the following:

如果你想使用abind,那么使用以下内容:

> library(abind)
> apply(abind(Lists, along=3), c(1,2), prod)
     [,1] [,2]
[1,]   50  252
[2,]  132  416

#1


13  

Use Reduce if you want an element-by-element multiplication

如果需要逐个元素乘法,请使用Reduce

> Lists <- list(matrix(1:4, 2), matrix(5:8, 2), matrix(10:13, 2))
> Reduce("*", Lists)
     [,1] [,2]
[1,]   50  252
[2,]  132  416

Instead of using abind you can use simplify2array function and apply

您可以使用simplify2array函数并应用而不是使用abind

> apply(simplify2array(Lists), c(1,2), prod)
     [,1] [,2]
[1,]   50  252
[2,]  132  416

If you want to use abind then use the following:

如果你想使用abind,那么使用以下内容:

> library(abind)
> apply(abind(Lists, along=3), c(1,2), prod)
     [,1] [,2]
[1,]   50  252
[2,]  132  416