olamundo
olamundo

Reputation: 24981

Matlab: Sum elements in array into another array

Suppose I have an array age=[16 17 25 18 32 89 43 55] which holds the ages of a certain list of people. I also have a second array called groups=[1 1 2 1 3 2 1 4] denotes to which group each person belongs, i.e the person whose age is 55 is the only person in group 4, there are three people in group 1 etc.

I want to calculate the combined sum of ages in each group. That is, the result I want to get in this case is an array of 4 elements, it's first entry containing the sum of ages of people belonging to group #1 (16+17+18+43), second entry containing the sum of ages of people belonging to group #2 (23+89) etc.

I know of course how to do this with a for loop, but is it possible to do this using some variation of sum or something similar, so as to tap into matlab's vector optimization?

Upvotes: 1

Views: 869

Answers (2)

Sam Roberts
Sam Roberts

Reputation: 24127

The code in @Ismail's answer is fine, but you could also try this:

>> accumarray(groups', age')
ans =
    94
   114
    32
    55

I find it hard to get an appreciation from the documentation exactly what accumarray can do in its full generality, but this is a great example of a simple usage. It's worth learning how to use it effectively, as once you've worked it out it's very powerful - and it will be a lot faster (when used on a larger example) than arrayfun.

Upvotes: 4

petrichor
petrichor

Reputation: 6579

You can use arrayfun and unique as follows:

arrayfun(@(x) sum(age(groups==x)), unique(groups))

Upvotes: 2

Related Questions