【问题标题】:cumulative sum of multiple matrices in rr中多个矩阵的累积和
【发布时间】:2016-09-06 01:10:15
【问题描述】:

假设我有一个由 3 个矩阵组成的数组。

set.seed(1)
array1<-array(sample(1:50,18), dim=c(2,3,3))
, , 1
     [,1] [,2] [,3]
[1,]   14   28   10
[2,]   19   43   41
, , 2
     [,1] [,2] [,3]
[1,]   42   27    9
[2,]   29    3    7
, , 3
     [,1] [,2] [,3]
[1,]   44   48   25
[2,]   15   18   33

我需要的是两个矩阵累积矩阵,一个是前两个矩阵的和,另一个是三个矩阵的和。显然,我可以通过计算两个矩阵的和来简单地得到它们。

array1[,,1]+array1[,,2]
     [,1] [,2] [,3]
[1,]   56   55   19
[2,]   48   46   48

array1[,,1]+array1[,,2]+array1[,,3]
     [,1] [,2] [,3]
[1,]  100  103   44
[2,]   63   64   81

但是,我想知道一种使用简单函数生成累积矩阵的方法,以防有很多矩阵。

谢谢。

【问题讨论】:

  • 我们可以使用apply,即apply(array1, c(1,2), sum)
  • @akrun 谢谢,但它只给出了最后一个矩阵,而我需要两者都有。

标签: r matrix


【解决方案1】:

我们可以使用applyMARGIN 并得到sum

apply(array1[,,1:2], c(1,2), sum)
#     [,1] [,2] [,3]
#[1,]   56   55   19
#[2,]   48   46   48

apply(array1, c(1,2), sum)
#     [,1] [,2] [,3]
#[1,]  100  103   44
#[2,]   63   64   81

或者我们指定MARGIN=1并得到rowSums

t(apply(array1[,, 1:2], 1, rowSums))
t(apply(array1, 1, rowSums))

或者另一种选择是在初始化输出矩阵 ('r2') 后的 for 循环

r2 <- matrix(0, nrow = nrow(array1[,,1]), ncol = ncol(array1[,,1]))
for(j in seq(dim(array1)[3])){
     r2 <- r2 + array1[,,j]
 }
r2
#    [,1] [,2] [,3]
#[1,]  100  103   44
#[2,]   63   64   81

对于第一种情况,在for 循环中使用head(seq(dim(array1)[3]),2),而不是seq(dim(array1)[3])

【讨论】:

    【解决方案2】:

    只是为您的具体示例添加 akrun 的方法,用于在数组中创建和求和的函数形式将是:

    set.seed(1)
    SumMatrices<-function(beginSum,endSum,n){
    matrixArray<-array(sample(1:50,6*n), dim=c(2,3,n)) 
    #where 6 is the product of the first two dimensions - 2*3,
    #and 1:50 are the limits of the random number generation
    apply(matrixArray[,,beginSum:endSum], c(1,2), sum)
    #beginSum and endSum are the matrices within the array you would
    #like to sum
    }
    SumMatrices(1,2,3)
    

    当然,这也可以推广,因此用户可以将数组中的矩阵设置为他们想要的任何维度:

    set.seed(1)
    SumMatrices<-function(beginSum,endSum,x,y,n){
    matrixArray<-array(sample(1:50,x*y*n), dim=c(x,y,n)) 
    apply(matrixArray[,,beginSum:endSum], c(1,2), sum)
    }
    SumMatrices(1,2,2,3,3)
    

    希望这能回答你的问题!

    【讨论】:

      猜你喜欢
      • 2012-11-11
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-12-14
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多