MATLAB: How do you determine the average values in second column of a matrix if values in first column are equal

matrix manipulationmean

I would like to average values in the second column of a matrix that correspond to equal (and unique) values in the first column, a simple example:
a= [0.4000 0.5000
0.4000 0.4500
0.4000 0.6000
0.6000 1.0000
0.6000 1.2000
1.2000 3.0000
1.2000 3.5000
1.2000 3.0000];
should become…
b = [0.4000 0.5167
0.6000 1.1000
1.2000 3.1667];
Also, is there a non-loop way to do this, for matrices with thousands of elements?
Thank you!

Best Answer

a= [0.4000 0.5000
0.4000 0.4500
0.4000 0.6000
0.6000 1.0000
0.6000 1.2000
1.2000 3.0000
1.2000 3.5000
1.2000 3.0000];
[G,aa] = findgroups(a(:,1));
b = [ aa, splitapply(@mean,a(:,2),G)]
or our old variant
[aa,~,c] = unique(a(:,1));
b = [aa, accumarray(c,a(:,2),[],@mean);