简体   繁体   English

如何对一系列矩阵求和?

[英]How do I sum a sequence of matrices?

so say I had a matrix所以说我有一个矩阵

> A<-matrix(c(5,1,3,5,6,6,7,8,5),nrow=3,ncol=3)
> A
     [,1] [,2] [,3]
[1,]    5    5    7
[2,]    1    6    8
[3,]    3    6    5


and I wanted to take the sum of i from 1 to 3 multiplied by each corresponding column.我想将 i 从 1 到 3 的总和乘以每个相应的列。

so like很喜欢

for (i in 1:3){
i*A[,i]
something 
}

then there is more code after this that I cant seem to figure out however simple it may seem, goal is to sum 1* first column + 2* second column + 3* 3rd column using some sort of iterative loop with i.然后在此之后还有更多代码,我似乎无法弄清楚它看起来多么简单,目标是使用某种迭代循环将 1* 第一列 + 2* 第二列 + 3* 第三列与 i 相加。

If you are looking for a for loop version, maybe you can try the code below如果您正在寻找for循环版本,也许您可以尝试下面的代码

s <- 0
for (i in 1:3) {
  s <- s + i*A[,i,drop = FALSE]
}

such that这样

> s
     [,1]
[1,]   36
[2,]   37
[3,]   30

As mentioned by @eastclintw00d in the comment, a simple way is using matrix multiplication正如@eastclintw00d 在评论中提到的,一种简单的方法是使用矩阵乘法

> A%*% 1:3
     [,1]
[1,]   36
[2,]   37
[3,]   30

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM