MATLAB: Calculate median with accumarray

accumarrayhistcMATLABmediansort

Hello,
I have an array with two columns. The rows are sorted by the values of the first column and then indexed by the use of histc. Now I want to calculate the median of every interval for the columns. Procedure for the first column is clear with accumarray but before calculating the median for the second column I have to sort every interval, right? How can I do this?
groupMedian = accumarray(ID,Measurement(:,2),[],@median);

Best Answer

No, you do not need to sort each interval. Just make sure that each interval is given a distinct ID vector row.
[unique_col1, ~, ID] = unique(Measurement(:,1));
group_median = accumarray(ID, Measurement(:,2), [], @median);
output = [unique_col1, group_median];
No sorting by column 1 beforehand is needed (unless you happen to need that output for a different purpose.)