Summer Gleek
Summer Gleek

Reputation: 344

Sum columns in a matrix

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

so like 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

Upvotes: 4

Views: 489

Answers (2)

Steve
Steve

Reputation: 1587

Theoretically you can achieve this by right-multiplying by an upper triangular matrix of ones (of 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 |

Upvotes: 0

DatamineR
DatamineR

Reputation: 9628

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

Upvotes: 5

Related Questions