erogol
erogol

Reputation: 13614

how to sum matrix entities as indexing by another vector values?

Suppose I have a vector B=[1 1 2 2] and A=[5 6 7 4] in the form of B says the numbers in the A that are need to be summed up. That is we need to sum 5 and 6 as the first entry of the result array and sum 7 and 4 as the second entry. If B is [1 2 1 2] then first element of the result is 5+7 and second element is 6+4.

How could I do it in Matlab in generic sense?

Upvotes: 0

Views: 226

Answers (2)

Oleg
Oleg

Reputation: 10676

A fexible and general approach would be to use accumarray().

accumarray(B',A')

The function accumulates the values in A into the positions specified by B.

Since the documentation is not simple to understand I will summarize why it is flexible. You can:

  • choose your accumulating function (sum by default)
  • specify the positions as a set of coordinates for accumulation into ND arrays
  • preset the dimension of the accumulated array (by default it expands to max position)
  • pad with custom values the non accumulated positions (pads with 0 by default)
  • set the accumulated array to sparse, thus potential avoiding out of memory

Upvotes: 4

fpe
fpe

Reputation: 2750

[sum(A(1:2:end));sum(A(2:2:end))]

Upvotes: 0

Related Questions