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!
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)) ]
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With