Sum of columns in a matrix

I want to add columns 1: i of the matrix to get the cumulative sum of each. and then put the results into another matrix

so having:

matrix
    [,1] [,2] [,3] [,4] [,5]
[1,]  A   B    C    D    E
[2,]  F   G    H    I    J
[3,]  K   L    M    N    O
[4,]  P   Q    R    S    T

      

become:

newmatrix
    [,1]  [,2] [,3]     [,4]     [,5]
[1,]  A   A+B  A+B+C  A+B+C+D  A+B+C+D+E  
[2,]  F   F+G  F+G+H  F+G+H+I  F+G+H+I+J
[3,]  K   K+L  K+L+M  K+L+M+N  K+L+M+N+O
[4,]  P   P+Q  P+Q+R  P+Q+R+S  P+Q+R+S+T

      

+3


source to share


2 answers


> m<-matrix(rep(1:5,each=4),ncol=5)
> t(apply(m,1,cumsum))

      



+5


source


In theory, you can achieve this by right multiplying by the upper triangular matrix from (size m-by-m where the original matrix is ​​n-by-m)

| A B C D |   | 1 1 1 1 |   | A  A+B  A+B+C A+B+C+D |
| E F G H | * | 0 1 1 1 | = | E  E+F  E+F+G E+F+G+H |
| I J K L |   | 0 0 1 1 |   | I  I+J  I+J+K I+J+K+L |
              | 0 0 0 1 |

      



or

| A B C D E |   | 1 1 1 1 1 |   | A A+B A+B+C A+B+C+D A+B+C+D+E |
| F G H I J |   | 0 1 1 1 1 |   | F F+G F+G+H F+G+H+I F+G+H+I+J |
| K L M N O | * | 0 0 1 1 1 | = | K K+L K+L+M K+L+M+N K+L+M+N+O |
| P Q R S T |   | 0 0 0 1 1 |   | P P+Q P+Q+R P+Q+R+S P+Q+R+S+T |
                | 0 0 0 0 1 |

      

0


source







All Articles