如果矩阵存储在R中的列表中,如何乘以矩阵元素?

如果矩阵存储在列表中,则要乘以矩阵元素,我们可以使用Reduce函数。例如,如果我们有四个名为M1,M2,M3和M4的矩阵存储在名为List的列表对象中,那么可以使用命令Reduce(“ *”,List)完成所有四个矩阵中每个元素的相乘。 。

例1

M1<−matrix(rpois(16,5),nrow=4)

M2<−matrix(rpois(16,5),nrow=4)

M3<−matrix(rpois(16,5),nrow=4)

M4<−matrix(rpois(16,5),nrow=4)

List1<−list(M1,M2,M3,M4)

List1

输出结果
[[1]]

[,1] [,2] [,3] [,4]

[1,] 6 2 7 7

[2,] 5 5 3 6

[3,] 4 5 4 5

[4,] 4 5 5 6

[[2]]

[,1] [,2] [,3] [,4]

[1,] 6 1 4 5

[2,] 3 3 2 7

[3,] 4 6 6 2

[4,] 5 4 5 1

[[3]]

[,1] [,2] [,3] [,4]

[1,] 5 8 4 3

[2,] 6 3 4 7

[3,] 3 4 6 6

[4,] 8 4 6 5

[[4]]

[,1] [,2] [,3] [,4]

[1,] 8 5 6 3

[2,] 5 8 5 6

[3,] 5 6 6 6

[4,] 6 3 7 4

示例

Reduce("*",List1)
输出结果
    [,1]  [,2] [,3] [,4]

[1,] 1440  80  672   315

[2,] 450  360  120   1764

[3,] 240  720  864   360

[4,] 960  240  1050  120

例2

M5<−matrix(rnorm(16),nrow=4)

M6<−matrix(rnorm(16),nrow=4)

M7<−matrix(rnorm(16),nrow=4)

M8<−matrix(rnorm(16),nrow=4)

List2<−list(M5,M6,M7,M8)

List2

输出结果
[[1]]

[,1] [,2] [,3] [,4]

[1,] −1.17500558 −0.3789481 1.2981585 1.5304519

[2,] −0.33537105 −0.4601639 1.0195614 −1.7230808

[3,] −0.57899091 0.4287061 0.3032158 −0.6126850

[4,] 0.03140941 0.4583744 0.7866852 −0.1935998

[[2]]

[,1] [,2] [,3] [,4]

[1,] −0.1394339 0.6452931 −1.458856 −1.4520165

[2,] 0.7778936 0.3316287 −1.059017 −0.8774907

[3,] −0.0217808 −1.0909818 1.522260 −1.8202440

[4,] −0.2098468 1.7168821 1.077953 −1.2487498

[[3]]

[,1] [,2] [,3] [,4]

[1,] −0.3480945 0.6093628 1.787201 0.68324551

[2,] −0.8298829 −0.3769359 −2.241507 0.25608527

[3,] −0.2502319 −0.9952626 −1.003563 −0.14128627

[4,] −0.5800064 0.1270392 −2.348742 −0.02443073

[[4]]

[,1] [,2] [,3] [,4]

[1,] 0.48629108 0.9983532 0.09931089 −2.0465883

[2,] 0.64408048 −0.6223245 0.97689259 −0.1141492

[3,] −0.08891064 −0.4889505 0.74757018 −1.0521619

[4,] 1.07069199 −0.7117454 1.10459033 0.5326226

示例

Reduce("*",List2)
输出结果
[,1] [,2] [,3] [,4]

[1,] −0.0277333189 −0.14876368 −0.3361325 3.107409654

[2,] 0.1394449283 −0.03579720 2.3643025 −0.044198320

[3,] 0.0002805705 −0.22760390 −0.3462877 0.165786599

[4,] 0.0040931664 −0.07115793 −2.2000741 −0.003145837

以上是 如果矩阵存储在R中的列表中,如何乘以矩阵元素? 的全部内容, 来源链接: utcz.com/z/342697.html

回到顶部