Add column of group sum to the right of matrix
4 visualizzazioni (ultimi 30 giorni)
Mostra commenti meno recenti
I have a large matrix and want to add group sum to the right. I would like to create group sum based on a first and second column of the matrix, add it to the right side of the matrix.
Below is the part of my matrix. I would like to add a column with the sum of 5th column grouped by first and second column. In below data, with the combination of first and second column, there are two distinct groups (1,1) and (1,2). Sum of values in 5th column (1,0,3,,,) for the first group (1,1) is 40 and the sum of values in 5th column (0,1,5,2,,) for the second group (1,2) is 29.
1 1 1 1 1
1 1 1 2 0
1 1 1 3 3
1 1 1 4 4
1 1 1 5 6
1 1 1 6 0
1 1 1 7 4
1 1 1 8 2
1 1 1 9 12
1 1 1 10 3
1 1 1 11 0
1 1 1 12 5
1 2 1 1 0
1 2 1 2 1
1 2 1 3 5
1 2 1 4 2
1 2 1 5 2
1 2 1 6 4
1 2 1 7 0
1 2 1 8 9
1 2 1 9 1
1 2 1 10 3
1 2 1 11 2
1 2 1 12 0
So, my desiring output is
1 1 1 1 1 40
1 1 1 2 0 40
1 1 1 3 3 40
1 1 1 4 4 40
1 1 1 5 6 40
1 1 1 6 0 40
1 1 1 7 4 40
1 1 1 8 2 40
1 1 1 9 12 40
1 1 1 10 3 40
1 1 1 11 0 40
1 1 1 12 5 40
1 2 1 1 0 29
1 2 1 2 1 29
1 2 1 3 5 29
1 2 1 4 2 29
1 2 1 5 2 29
1 2 1 6 4 29
1 2 1 7 0 29
1 2 1 8 9 29
1 2 1 9 1 29
1 2 1 10 3 29
1 2 1 11 2 29
1 2 1 12 0 29
0 Commenti
Risposte (1)
Guillaume
il 30 Apr 2018
[~, ~, uid] = unique(yourmatrix(:, [1 2]), 'rows');
uidsum = accumarray(uid, yourmatrix(:, 5));
yourmatrix(:, 6) = uidsum(uid)
will work even if column 1 and 2 are not ordered.
0 Commenti
Vedere anche
Categorie
Scopri di più su Creating and Concatenating Matrices in Help Center e File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!