Cumulative sum in a matrix

前端 未结 2 1643
粉色の甜心
粉色の甜心 2021-01-11 09:51

I have a matrix like

A= [ 1 2 4
     2 3 1
     3 1 2 ]

and I would like to calculate its cumulative sum by row and by column, that is, I w

2条回答
  •  梦谈多话
    2021-01-11 10:36

    Here is a more efficient implementation using the matrixStats package and a larger example matrix:

    library(matrixStats)
    A <- matrix(runif(10000*10000, 1, 500), 10000)
    
    # Thilo's answer
    system.time(B <- t(apply(apply(A, 2, cumsum), 1, cumsum)))
    user  system elapsed 
    3.684   0.504   4.201
    
    # using matrixStats
    system.time(C <- colCumsums(rowCumsums(A)))
    user  system elapsed 
    0.164   0.068   0.233 
    
    all.equal(B, C)
    [1] TRUE
    

提交回复
热议问题