Summing common elements of a matrix together
古いコメントを表示
Suppose I have a matrix
A = [1 1 2 2 3 3 3]
and
B = [1 2 3 4 5 6 7]
I want to create a matrix which sums the elements of B, by grouping them according to A, which means:
sum = [3 7 18]
which we got by: from B, we took 1, 2 because A matrix tells us that first two elements belong to first group, similarly 3, 4 for second and 5, 6, 7 for the third. Is there a non-loop way to do this?
採用された回答
その他の回答 (1 件)
Onomitra Ghosh
2012 年 3 月 21 日
May be something like:
A = [1 1 2 2 3 3 3];
B = [1 2 3 4 5 6 7];
C = [];
for idx = unique(A)
C(end+1) = sum(B(A==idx));
end
C
2 件のコメント
Vinay Pandey
2012 年 3 月 21 日
Onomitra Ghosh
2012 年 3 月 22 日
I have not tried it; it might be difficult to get rid of the loop because it is not straightforward vectorization.
カテゴリ
ヘルプ センター および File Exchange で Creating and Concatenating Matrices についてさらに検索
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!