Sum according to the values in another column

18 ビュー (過去 30 日間)
Aragorn23
Aragorn23 2019 年 7 月 10 日
コメント済み: Aragorn23 2019 年 7 月 10 日
Hi everyone,
I have two columns, with the same amount of elements.
C1 = 1-1-1-1-1-2-2-2-2-2-2-3-3-3-4-4-4-4
C2 = 5-10-12-35-3-1-4-26-5-11-12-8-2-22-8-2-5-7
I would like to sum the values of C2 according to C1, and present the results like that:
1 - 65;
2 - 59
3 - 32
4 - 22
How can I do that?

採用された回答

Steven Lord
Steven Lord 2019 年 7 月 10 日
Use groupsummary.
C1 = [1 1 1 1 1 2 2 2 2 2 2 3 3 3 4 4 4 4].';
C2 = [5 10 12 35 3 1 4 26 5 11 12 8 2 22 8 2 5 7].';
[binvalues, bingroups] = groupsummary(C2, C1, @sum)
This applies the sum function to each group of elements in C2 for which the corresponding values in C1 are the same. Each element of binvalues is the sum of the elements in C2 for the bin in the corresponding element of bingroups.
The elements of C1 don't need to be positive integers; I could have grouped the values corresponding to bins associated with C1+1.5 if I wanted.
  1 件のコメント
Aragorn23
Aragorn23 2019 年 7 月 10 日
Thank you Steven.

サインインしてコメントする。

その他の回答 (1 件)

madhan ravi
madhan ravi 2019 年 7 月 10 日
編集済み: madhan ravi 2019 年 7 月 10 日
[u,~,idx]=unique(C1(:));
Wanted = [u,accumarray(idx,C2,[],@sum)]
  3 件のコメント
madhan ravi
madhan ravi 2019 年 7 月 10 日
Oh thank you Guillaume :)
Aragorn23
Aragorn23 2019 年 7 月 10 日
Thank you, guys.

サインインしてコメントする。

カテゴリ

Help Center および File ExchangeLanguage Fundamentals についてさらに検索

Community Treasure Hunt

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

Start Hunting!

Translated by