MATLAB: How to reorder the rows by sorting the elements of column in ascending order

arraycolumnmatrixreorderrowsort

Hi everyone,
I have id=[ 1 3 2; 2 6 4; 3 2 6; 4 5 1; 5 1 3; 6 4 5; 7 7 7]
j=1:3
I want to reorder the rows of id by sorting the jth column of id such that the elements in this column are sorted from small to large.
Where my result will get j set of number.
id1=[ 1 3 2; 2 6 4; 3 2 6; 4 5 1; 5 1 3; 6 4 5; 7 7 7]
id2=[5 1 3; 3 2 6; 1 3 2; 6 4 5; 4 5 1; 2 6 4; 7 7 7]
id3=[4 5 1; 1 3 2; 5 1 3; 2 6 4; 6 4 5; 3 2 6; 7 7 7 ]
How can i do this?
Thanks.

Best Answer

  • for c=1:3
    is(1)={sortrows(id,i)};
    end
    using a cell array to hold results; use a dynamic named structure field if desired
    Alternatively, arrayfun is your friend for such things...
    idsrted=arrayfun(@(c) sortrows(id,c),[1:3],'uniform',0);