Sum elements in the first column according to repeated values in a second column
10 ビュー (過去 30 日間)
古いコメントを表示
Hi, I have a two columns matrix, where the elements of the second column are repeated (here below in my example, 55, 98 and 17 are repeated several times).
I would like to sum the elements of the first column, which have (in common) the same element of the second column. Here an example... any fast way to do it?
% Input
A = [ 4 55
3 55
7 55
1 55
9 98
1 98
2 98
8 98
0 98
1 98
6 17
3 17
0 17
4 17]
% desired output
B = [15 55
21 98
13 17];
where, for example, the value 15 in B(1,1) is given by 4 + 3 + 7 + 1 = 15
0 件のコメント
採用された回答
Star Strider
2022 年 3 月 2 日
A = [ 4 55
3 55
7 55
1 55
9 98
1 98
2 98
8 98
0 98
1 98
6 17
3 17
0 17
4 17];
[A2u,~,ix] = unique(A(:,2));
A1sums = accumarray(ix,A(:,1),[],@sum);
Desired_Result = [A1sums A2u]
.
4 件のコメント
Johan
2022 年 3 月 4 日
I figured a pretty obfuscated way to do that without for loop; note that it's slower than using accumarray :)
A = [ 4 55
3 55
7 55
1 55
9 98
1 98
2 98
8 98
0 98
1 98
6 17
3 17
0 17
4 17];
logicalmask = A(:,2) == unique(A(:,2))';
result = [sum(A(:,1).*logicalmask)',unique(A(:,2))]
その他の回答 (1 件)
参考
カテゴリ
Help Center および File Exchange で Numeric Types についてさらに検索
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!