tags:

views:

65

answers:

2

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

How can I do it, if instead of a list I have those matrices in a (2 x 2 x n) dimensional array ?

+2  A: 

I would mess with arrays so if you got a list e.g.:

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

transform it to 3d array

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

Now you could use rowSums

rowSums(someArray, dims=2)
#      [,1] [,2]
# [1,]   45   55
# [2,]   50   60
Marek
I was close to find this. It's that `dims` parameter that I was missing.
Brani
+5  A: 

Sum of matrices in a list:

Reduce("+", matrix_list)
rcs
Very elegant. I tried `do.call` without success. I think that I must try to understand and use the `Reduce` function.
Brani
Anyone know why all the functional programming functions like `Map` and `Reduce` are capitalized?
Vince