Reputation: 51
So if i have an number array:
a b
1 2.5
1 1.2
3 2.5
4 0.4
6 3
3 1.2
i want to sum up numbers in column a with same value of of b in column 2, like this:
a b
4 2.5
4 1.2
4 0.4
6 3
so as you can see 1 and 3 add up and became 4, because they have the same value of b which is 2 and also to the rest of the numbers, so how i will do that? thanks (PS: my real data is combination of integers and decimal no. thanks)
Upvotes: 0
Views: 181
Reputation: 221574
Assuming A
to be the input array, you have two approaches to play with here.
Approach #1
A combination of accumarray
and unique
-
[unqcol2,~,idx] = unique(A(:,2),'stable')
[accumarray(idx,A(:,1)) unqcol2]
Approach #2
With bsxfun
-
[unqcol2,~,idx] = unique(A(:,2),'stable')
[sum(bsxfun(@times,bsxfun(@eq,idx,1:max(idx)),A(:,1)),1).' unqcol2 ]
Upvotes: 3