R programming to find the sum of corresponding elements in all matrix’s stored in a list.

R ProgrammingServer Side ProgrammingProgramming

To find the sum of corresponding elements in all matrix’s stored in a list in R, we can use Reduce function with plus sign. For Example, if we have a list called LIST that contains multiple matrices and we want to find the sum of corresponding elements then we can use the command given below −

Reduce("+",LIST)

Check out the below Examples to understand how it works.

Example 1

To find the sum of corresponding elements in all matrix’s stored in a list in R, use the following snippet −

List<-
list(M1=matrix(round(rnorm(40),2),ncol=2),M2=matrix(round(rnorm(40),2),ncol=2),M3=matrix(round(rnorm(40),2),ncol=2))
List

The following matrices are created −

$M1
       [,1]  [,2]
 [1,] -0.34 -2.36
 [2,]  0.33  1.17
 [3,]  1.05  1.97
 [4,]  0.46  1.09
 [5,]  0.34  0.45
 [6,]  0.78  1.43
 [7,] -0.07 -0.08
 [8,]  0.29 -1.13
 [9,] -0.62  0.72
[10,]  1.85  0.82
[11,] -0.08 -0.85
[12,]  0.14 -0.47
[13,]  1.16 -0.46
[14,]  0.88  0.95
[15,] -0.68 -2.30
[16,]  1.12  0.35
[17,]  0.06 -1.29
[18,]  0.78 -0.64
[19,] -0.36  0.07
[20,] -0.62  0.72
$M2
       [,1]  [,2]
 [1,] -0.17  0.39
 [2,] -0.83  0.45
 [3,]  0.64  0.50
 [4,]  0.13 -1.00
 [5,] -0.33  0.63
 [6,]  0.71  1.12
 [7,]  0.50  2.67
 [8,] -0.86 -0.49
 [9,]  0.94  0.75
[10,] -0.20  0.14
[11,]  1.37 -1.53
[12,] -0.94  0.43
[13,] -1.65  0.66
[14,]  1.27 -0.68
[15,] -0.07 -0.62
[16,] -0.82  0.06
[17,] -1.48  0.48
[18,]  0.82  0.11
[19,] -0.05 -0.01
[20,]  1.05  0.64
$M3
       [,1]  [,2]
 [1,] -1.49  0.49
 [2,]  0.09 -0.73
 [3,] -2.62  1.38
 [4,]  0.72 -0.01
 [5,] -1.28  0.01
 [6,] -0.80  0.41
 [7,]  0.14  0.47
 [8,] -0.34  0.34
 [9,] -0.72  1.05
[10,] -0.74 -0.70
[11,] -0.33  0.00
[12,]  0.89  0.26
[13,]  0.17 -0.30
[14,] -1.22 -0.91
[15,] -0.74 -0.05
[16,] -1.81  1.02
[17,]  0.88  0.41
[18,] -2.10 -0.16
[19,] -0.31  0.67
[20,] -1.00  1.76

To find the sum of corresponding elements of matrices stored in List on the above created matrices, add the following code to the above snippet −

List<-
list(M1=matrix(round(rnorm(40),2),ncol=2),M2=matrix(round(rnorm(40),2),ncol=2),M3=matrix(round(rnorm(40),2),ncol=2))
Reduce("+",List)

Output

If you execute all the above given snippets as a single program, it generates the following Output −

       [,1] [,2]
 [1,] -2.00 -1.48
 [2,] -0.41  0.89
 [3,] -0.93  3.85
 [4,]  1.31  0.08
 [5,] -1.27  1.09
 [6,]  0.69  2.96
 [7,]  0.57  3.06
 [8,] -0.91 -1.28
 [9,] -0.40  2.52
[10,]  0.91  0.26
[11,]  0.96 -2.38
[12,]  0.09  0.22
[13,] -0.32 -0.10
[14,]  0.93 -0.64
[15,] -1.49 -2.97
[16,] -1.51  1.43
[17,] -0.54 -0.40
[18,] -0.50 -0.69
[19,] -0.72  0.73
[20,] -0.57  3.12
raja
Updated on 08-Nov-2021 07:54:36

Advertisements