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

1 次查看(过去 30 天)
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

采纳的回答

Star Strider
Star Strider 2016-8-18
编辑:Star Strider 2016-8-18
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 个评论
Star Strider
Star Strider 2016-8-18
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.

请先登录,再进行评论。

更多回答(0 个)

类别

Help CenterFile Exchange 中查找有关 Just for fun 的更多信息

产品

Community Treasure Hunt

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

Start Hunting!

Translated by