0

I have an array with 272 matrices, each one is 2 by 2. I now want to sum these matrices up using matrix addition. So I want the return to be a single 2 by 2 matrix. Here are some code I have used.

 y <- as.matrix(faithful) 
 B <- matrix(c(0,0,0,0),nrow = 2)


 sigma <- function(n = 272,u_new) {
     vec = replicate(272,B)

     for (i in 1:n) {

w <- (y-u_new)[i,]
x <- ptilde1[i]*(w%*%t(w))
vec[,,i][1,1] <- x[1,1]
vec[,,i][1,2] <- x[1,2]
vec[,,i][2,1] <- x[2,1]
vec[,,i][2,2] <- x[2,2]}

  vec
  }

Here vec is the array with 272 matrices. Thank you in advance.

Rann
  • 315
  • 1
  • 4
  • 11
  • 1
    Possible duplicate of [Sum a list of matrices](http://stackoverflow.com/questions/11641701/sum-a-list-of-matrices) – Tim Biegeleisen Nov 24 '15 at 05:18
  • @TimBiegeleisen, I tried that. It didn't work, returned me one single number instead. I guess that's because my vec is an array. not a list, andI don't know how to build a list of matrices. – Rann Nov 24 '15 at 05:25

1 Answers1

0

Here is code which loops a number of times (272) and adds a matrix to the same list.

B <- matrix(c(0,0,0,0),nrow = 2)
list <- list(B)
for (i in 2:272) {
    list[[i]] <- B
}

To add them all together, you can use the Reduce() function:

sum <- Reduce('+', list)
> sum
     [,1] [,2]
[1,]    0    0
[2,]    0    0

This is a contrived example because all the matrices are the zero matrix. I will leave it to you as a homework assignment to use the matrices you actually want to sum together.

Tim Biegeleisen
  • 502,043
  • 27
  • 286
  • 360