0

I have a matrix

       i     j    values
  a =  1     2    10
       1     2    20
       2     1    11
       2     2    10
       2     1     1

I want to merge rows for the matrix a based on the first two columns where the first two columns have same values. The result should look like

res =

 1     2    30
 2     1    12
 2     2    10

Is it possible to do this without loops?

Thanks

Stewie Griffin
  • 14,889
  • 11
  • 39
  • 70

1 Answers1

0

Retrieve unique pairs of the first two columns, then use the indices that map all of the rows in a to the unique pairs and finally accumulate according to the mapping the values in the third column:

[un, ~, subs] = unique(a(:,1:2),'rows');
[un accumarray(subs,a(:,3))]
Oleg
  • 10,406
  • 3
  • 29
  • 57