%% Sort Rows of Matrix
% Create a matrix and sort its rows in ascending order based on the elements in the first column. When the first column contains repeated elements, sortrows looks to the elements in the second column to break the tie.  For repeated elements in the second column, sortrows looks to the third column, and so on.

rng default;
A = floor(rand([6 7])*100);
A(1:4,1) = 95;  A(5:6,1) = 76;  A(2:4,2) = 7;  A(3,3) = 48

%

B = sortrows(A) 

%
% Sort the rows of A based on the values in the second column. When the specified column has repeated elements, the corresponding rows maintain their original order.

C = sortrows(A,2)

%
% Sort the rows of A based on the elements in the first column, and look to the seventh column to break any ties.

D = sortrows(A,[1 7])

%
% Sort the rows of A in descending order based on the elements in the fourth column, and display the output vector index to see how the rows were rearranged.

[E,index] = sortrows(A,4,'descend')

%
% Copyright 2012 The MathWorks, Inc.