Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Sum rows in matrix whose first elements match?

I have the matrix:

a=[1 2
   2 3
   1 5
   3 4
   2 9];

I would like to simplify it by summing together the second column of rows whose first column element matches. Therefore the above matrix a should become:

a=[1 7
   2 12
   3 4];

I'm at a loss as to how to do this functionally, in other words without a for loop. Thank you!

like image 714
space_voyager Avatar asked May 04 '26 05:05

space_voyager


1 Answers

Use accumarray and unique:

[u,~,subs] = unique(a(:,1))
out = [ u, accumarray(subs,a(:,2)) ]

out =

     1     7
     2    12
     3     4

For the one-line solution, you'd need an external function:

function subs = unique3rdOutput( vec )
   [~,~,subs] = unique(vec)

And then

out = [ unique(a(:,1)), accumarray(unique3rdOutput(a(:,1)),a(:,2)) ]

If you can ensure just positive integers in the first column, you can also use:

out = [ unique(a(:,1)) accumarray(a(:,1),a(:,2)) ]

or as suggested by Luis Mendo:

out = [ (1:max(a(:,1))).' accumarray(a(:,1),a(:,2)) ]
like image 131
Robert Seifert Avatar answered May 06 '26 20:05

Robert Seifert