Calculate the sum of the matrices in a list or three-dimensional array

Given a list (length = n) of 2x2 matrices, how can I calculate the sum of all these matrices (and get a 2x2 matrix)?

How can I do this if instead of a list I have these matrices in a (2 x 2 xn) dimensional array?

+5
source share
2 answers

Sum of matrices in the list:

Reduce("+", matrix_list)
+7
source

I would use files with arrays, so if you have listfor example:

n <- 5
someList <- lapply(1:n, function(i) matrix(1:4+(i-1)*4,2,2))

convert it to 3d array

someArray <- array(unlist(someList ), c(2,2,n))

Now you can use rowSums

rowSums(someArray, dims=2)
#      [,1] [,2]
# [1,]   45   55
# [2,]   50   60
+4
source

All Articles