How do I get a sum of column two if the value in column one is the same?
1 visualizzazione (ultimi 30 giorni)
Mostra commenti meno recenti
Humblespud
il 18 Ago 2016
Commentato: Star Strider
il 18 Ago 2016
How do I get a sum of column two if the value in column one is the same? The values below represent a segment of a much larger dataset
31128 166 31128 27 31128 0 31128 276 31128 0 31201 0 31201 2125 31201 0 31201 56 31201 0 31201 0 31201 0 31201 0 31235 2125 31235 13 31235 364 31235 1836 31235 379 31235 486
0 Commenti
Risposta accettata
Star Strider
il 18 Ago 2016
Modificato: Star Strider
il 18 Ago 2016
Use the unique and accumarray functions:
A = [31128 166
31128 27
31128 0
31128 276
31128 0
31201 0
31201 2125
31201 0
31201 56
31201 0
31201 0
31201 0
31201 0
31235 2125
31235 13
31235 364
31235 1836
31235 379
31235 486];
[A1u,ia,ic] = unique(A(:,1));
A2sum = accumarray(ic, A(:,2));
Result = [A1u A2sum]
Result =
31128 469
31201 2181
31235 5203
2 Commenti
Star Strider
il 18 Ago 2016
The code works by first getting the unique values in ‘A(:,1)’ and returns them in ‘A1u’. The ‘ic’ vector are the positions in ‘A(:,1)’ that correspond to each of them, so a 1 in ‘ic’ corresponds to an occurrence of ‘31128’, a 2 to ‘31201’, and so for the rest (since I assume there will be more).
The accumarray call uses the indices returned in ‘ic’ to accumulate (sum) the corrsponding values in ‘A(:,2)’, and returns that vector in ‘A2sum’. (See the documentation for accumarray for the details of all it can do.)
The ‘Result’ assignment concatenates ‘A1u’ and ‘A2sum’ to form a sort of table to make the output easier to interpret.
Più risposte (0)
Vedere anche
Prodotti
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!