Filter löschen
Filter löschen

Summing common elements of a matrix together

1 Ansicht (letzte 30 Tage)
Vinay Pandey
Vinay Pandey am 21 Mär. 2012
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?

Akzeptierte Antwort

Oleg Komarov
Oleg Komarov am 22 Mär. 2012
accumarray(A.',B.')
  2 Kommentare
Geoff
Geoff am 22 Mär. 2012
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
Oleg Komarov am 22 Mär. 2012
You're not wrong, it just matters with complex numbers:
' -> ctranspose: complex conjugate transpose
.' -> transpose

Melden Sie sich an, um zu kommentieren.

Weitere Antworten (1)

Onomitra Ghosh
Onomitra Ghosh am 21 Mär. 2012
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 Kommentare
Vinay Pandey
Vinay Pandey am 21 Mär. 2012
Is there a way to remove the loop?
Onomitra Ghosh
Onomitra Ghosh am 22 Mär. 2012
I have not tried it; it might be difficult to get rid of the loop because it is not straightforward vectorization.

Melden Sie sich an, um zu kommentieren.

Kategorien

Mehr zu Multidimensional Arrays finden Sie in Help Center und File Exchange

Community Treasure Hunt

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

Start Hunting!

Translated by