MATLAB: Sortrows(A, [2 1[) is doing the 2nd round of sorting incorrectly.

sorting by multiple columnssortrows

I am trying to organize a large array based on x,y coordinates. I want the result to be sorted (ascending) by y-coordinate, then within each y-coordinate sorted (ascending) by x-coordinate. (These are the coordinates of a bridge model). The data is stored in an excel sheet (linked: https://skydrive.live.com/?cid=a19c139fd96328c1&id=A19C139FD96328C1%21177&action=Share#cid=A19C139FD96328C1&id=A19C139FD96328C1%21109). Code shown below:
%get data
coord=xlsread('coord_data.xlsx','Sheet1', 'A2:C4207');
%sort by y then x
coord_sort=sortrows(coord,[2,1]);
%write back to sheet
xlswrite('coord_data.xlsx', coord_sort,'Sheet1','E2');
The result is that the y's are sorted properly, but within each y-coordinate, the x's are a bit out of order. (If you were to actually run the code with the given excel data, going from cell E34 to E35, there is a jump with those numbers appearing at cell E136 instead).
I've tried different configurations using sortrows (ie I sorted by x then y in two separate commands) the x-sorting went well in that case, but when I subsequently sorted by y, got the same result.
Why might these problems be occurring?
Thank you. Joe Riddle

Best Answer

I see that your coordinates are listed using decimal fraction displays. I suggest a possible explanation for your apparent difficulties with 'sortrows'. Suppose that you have two rows in which the y values look the same in display but aren't exactly the same down in their least bits. Then the larger of these will occur later after sorting regardless of their associated x values. Just reading the results with ordinary display accuracy, it could look as if 'sortrows' "messed up".
Try displaying the apparently offending sections with 'format hex' which gives an exact (though difficult to interpret) reading of a number's value. Or perhaps use 'fprintf' with something like %28.20e format which can detect small differences.