Summing common elements of a matrix together
조회 수: 2 (최근 30일)
이전 댓글 표시
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?
댓글 수: 0
채택된 답변
Oleg Komarov
2012년 3월 22일
accumarray(A.',B.')
댓글 수: 2
Geoff
2012년 3월 22일
I've always used the syntax A' to transpose, but just checked the help for transpose() and see I'm apparently wrong! Is A' just an alias for A.', or is there some obscure difference?
Oleg Komarov
2012년 3월 22일
You're not wrong, it just matters with complex numbers:
' -> ctranspose: complex conjugate transpose
.' -> transpose
추가 답변 (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
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.
참고 항목
카테고리
Help Center 및 File Exchange에서 Matrices and Arrays에 대해 자세히 알아보기
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!