shecode
shecode

Reputation: 1726

How to do matrix calculations on related lists of matrices in R

I have two lists with two matrices in each list.. Is there a way to do matrix calculations on them i.e. adding, where the blue matrix from matrix1 adds the blue matrix from matrix2, and the red matrix from matrix1 ands the red matrix from matrix2 The only way I can think of is to do it within a loop

> mymatrix1
$blue
     [,1] [,2] [,3] [,4] [,5]
[1,]   10    1    2   13    1
[2,]    2   10   11   13   13
[3,]    3   14    1   15    9
[4,]    7   15   10    5    3
[5,]   12    8   11    3   13

$red
     [,1] [,2] [,3] [,4] [,5]
[1,]    4    9   14    7   10
[2,]   15    9    7   13   13
[3,]    8    8    9    6    6
[4,]    8   13   15    1    7
[5,]   12   13   10   14    2


> mymatrix2
$blue
     [,1] [,2] [,3] [,4] [,5]
[1,]   20    2    4   26    2
[2,]    4   20   22   26   26
[3,]    6   28    2   30   18
[4,]   14   30   20   10    6
[5,]   24   16   22    6   26

$red
     [,1] [,2] [,3] [,4] [,5]
[1,]   12   27   42   21   30
[2,]   45   27   21   39   39
[3,]   24   24   27   18   18
[4,]   24   39   45    3   21
[5,]   36   39   30   42    6

Please note I will have about 10 of these, and more than one group (i.e. blue, red, green, purple)

Upvotes: 2

Views: 73

Answers (1)

nrussell
nrussell

Reputation: 18612

UPDATE 2: For more than two lists:

mL1 <- list(
  blue = matrix(1:25,nrow=5),
  red = matrix(2*(1:25),nrow=5),
  green = matrix(3*(1:25),nrow=5),
  orange = matrix(4*(1:25),nrow=5)
)
mL2 <- mL1
mL3 <- mL1
##
Reduce(function(x,y){
    Map('+',x,y)
  },
  list(mL1,mL2,mL3),
  accumulate=F
)
$blue
     [,1] [,2] [,3] [,4] [,5]
[1,]    3   18   33   48   63
[2,]    6   21   36   51   66
[3,]    9   24   39   54   69
[4,]   12   27   42   57   72
[5,]   15   30   45   60   75

$red
     [,1] [,2] [,3] [,4] [,5]
[1,]    6   36   66   96  126
[2,]   12   42   72  102  132
[3,]   18   48   78  108  138
[4,]   24   54   84  114  144
[5,]   30   60   90  120  150

$green
     [,1] [,2] [,3] [,4] [,5]
[1,]    9   54   99  144  189
[2,]   18   63  108  153  198
[3,]   27   72  117  162  207
[4,]   36   81  126  171  216
[5,]   45   90  135  180  225

$orange
     [,1] [,2] [,3] [,4] [,5]
[1,]   12   72  132  192  252
[2,]   24   84  144  204  264
[3,]   36   96  156  216  276
[4,]   48  108  168  228  288
[5,]   60  120  180  240  300

Upvotes: 1

Related Questions