对矩阵列表求和 [英] Sum a list of matrices
本文介绍了对矩阵列表求和的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有一个列表,其中每个元素都是5 * 5矩阵.例如
I have a list where each element is a 5*5 matrix. Eg
[[1]]
V1 V2 V3 V4 V5
[1,] 0.000000 46.973700 21.453500 338.547000 10.401600
[2,] 43.020500 0.000000 130.652000 840.526000 56.363700
[3,] 12.605600 173.238000 0.000000 642.075000 19.628100
[4,] 217.946000 626.368000 481.329000 0.000000 642.341000
[5,] 217.946000 626.368000 481.329000 0.000000 642.341000
[[2]]
V1 V2 V3 V4 V5
[1,] 0.000000 47.973700 21.453500 338.547000 10.401600
[2,] 143.020500 0.000000 130.652000 840.526000 56.363700
[3,] 312.605600 17.238000 0.000000 642.075000 19.628100
[4,] 17.946000 126.368000 481.329000 0.000000 642.341000
[5,] 217.946000 626.368000 481.329000 0.000000 642.341000
...
如何使用类应用函数将矩阵[1]与[n]相加,并返回一个5 * 5矩阵作为结果(每个元素是矩阵中每个矩阵中对应元素的总和)列表)?
How can I use an apply-like function to sum matrix [1] to [n], and return a 5*5 matrix as a result (each element is a sum of the corresponding elements in each of the matrix in the list) ?
推荐答案
使用Reduce
.
## dummy data
.list <- list(matrix(1:25, ncol = 5), matrix(1:25, ncol = 5))
Reduce('+', .list)
## [,1] [,2] [,3] [,4] [,5]
## [1,] 2 12 22 32 42
## [2,] 4 14 24 34 44
## [3,] 6 16 26 36 46
## [4,] 8 18 28 38 48
## [5,] 10 20 30 40 50
这篇关于对矩阵列表求和的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文