MATLAB: Sum of two different data series

accumarrayaccumulateencoderun lengthsum

Hey all. I would like some help please on finding an efficient way of doing this:
I have two data series combined into one vector, so something like the below example
data =
DataPoint DataIdx
0.50 1
0.25 1
0.80 2
0.10 1
0.60 1
0.50 2
0.25 2
0.50 2
0.40 1
0.10 1
0.50 1
What I would like to do is add up all the data points per dataIdx, but preserve the order. So the output would be a "consolidated" vector which would look something like:
output =
DataConsolidated DataIdx
0.75 1
0.80 2
0.70 1
1.25 2
1.00 1
At the moment, I am using a for-loop that keeps a tally, but I hope there is a more elegant solution. I think this might lend itself well to an application of "accumarray", but I have not that much experience with this function. Any help pls?
Thanks! Hamad

Best Answer

A=[0.50 1
0.25 1
0.80 2
0.10 1
0.60 1
0.50 2
0.25 2
0.50 2
0.40 1
0.10 1
0.50 1 ]
jj=[0; diff(A(:,2))~=0];
kk=cumsum(jj);
[~,id]=unique(kk);
out=[ accumarray(kk+1,A(:,1)) A(id,2)]