MATLAB: Sort array elements in ascending order

sort array elements

Hello,
I have an input array which i want to sort column elements in ascending order
i =
[4 35;
2 4;
2 6 ;
1 9;
4 3 ;
4 6 ;
1 16;
3 17];
and get the sorted output array in the following manner
res=
[1 9;
1 16;
2 4;
2 6;
3 17;
4 3;
4 6;
4 35];
First sort according to the 1st column(ascending order),if the first column is same then check for the second column ,then sort in the acending order based on the second value.
For example : I have 1 as the least value in the first column and have two entries for 1. So check for the second element for 1. I have 9 and 16 as the second element for 1 respectively.Now sort these second elemnts in ascending order.so i have the output as [1 9; 1 16] .
Similary for all the other elements of the matrix.
Please let me know the MATLAB function for sorting the array elements and get me the required output as mentioned above.
Looking forward to hear from you
Thanks Pankaja

Best Answer

You can sort the rows and extract the minimum value of each "group" like this:
>> A = [8 4; 3 6; 2 7; 1 4; 2 3;2 1;3 1; 3 5; 8 6; 8 1];
>> B = sortrows(A);
>> X = [true;diff(B(:,1))>0];
>> B(X,:)
ans =
1 4
2 1
3 1
8 1
Where each row is the "minimum" of each group.