Monday, July 27, 2009

Matlab: grouping and add up values according to ID

OP here.

Q:
Suppose I have n x 3 matrix x, I want a piece of code that checks the first and second columns and if they are equal then it adds up the correponding values in the third column.

x = [
1 2 3; 1 2 5; 1 2 3;...
1 3 1; 1 3 1; 2 1 1;...
2 1 1; 2 1 2; 2 1 2]


The desired answer should be

y = [
1 2 11; 1 3 2; 2 1 6]


A:

[val, dump, idx] = unique(x(:,1:2),'rows')
y = [val, accumarray(idx,x(:,3))]

No comments: