How do I get a sum of column two if the value in column one is the same?

1 view (last 30 days)
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

Accepted Answer

Star Strider
Star Strider on 18 Aug 2016
Edited: Star Strider on 18 Aug 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 Comments
Humblespud
Humblespud on 18 Aug 2016
Edited: Star Strider on 18 Aug 2016
How would I get it that
Result =
Result =
31128 469
31201 2130
31235 5203
Star Strider
Star Strider on 18 Aug 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.

Sign in to comment.

More Answers (0)

Categories

Find more on Just for fun in Help Center and File Exchange

Products

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!