MATLAB: Find average of only directly repeating values in array

cell arraysunique

I have an array with two columns, that I want to clean up by finding the average value of column 1 for each unique value in column 2.
A = [
1 0.1
2 0.2
3 0.2
4 0.4
5 0.2 ]
I tried the unique function but have problems with repeating values (here 0.2 in the last row), so that in the above example I would not just calculate the average of rows 2 and 3, but of 2, 3 and 5. Is there a way to calculate the average of rows 2 and 3 separately from row 5?

Best Answer

ii = [true;diff(A(:,2)) ~= 0];
out = [accumarray(cumsum(ii),A(:,1),[],@mean),A(ii,2)];