www.gusucode.com > matlab 案例源码 matlab代码程序 > matlab/SortRowsofMatrixExample.m

    %% Sort Rows of Matrix  

%% 
% Start with an arbitrary matrix, |A|. 
A = floor(gallery('uniformdata',[6 7],0)*100);
A(1:4,1) = 95;  A(5:6,1) = 76;  A(2:4,2) = 7;  A(3,3) = 73  

%% 
% Sort the rows of |A|. 
B = sortrows(A) 

%%
% When called with only a single input argument, |sortrows| bases the sort
% on the first column of the matrix. For any rows that have equal elements
% in a particular column, (e.g., |A(1:4,1)| for this matrix), sorting is
% based on the column immediately to the right, (|A(1:4,2)| in this case).  

%% 
% When called with two input arguments, |sortrows| bases the sort entirely
% on the column specified in the second argument. 
%
% Sort the rows of |A| based on the values in the second column. 
C = sortrows(A,2) 

%%
% Rows that have equal elements in the specified column, (e.g., |A(2:4,:)|,
% if sorting matrix |A| by column 2) remain in their original order.  

%% 
% Specify two columns to sort by: columns 1 and 7. 
D = sortrows(A,[1 7]) 

%%
% |sortrows| sorts by column 1 first, and then for any rows with equal values
% in column 1, sorts by column 7.  

%% 
% Sort the rows in descending order using the values in column 4. 
[E,index] = sortrows(A, -4) 

%%
% The index vector, |index|, describes the rearrangement of the rows, such
% that |E = A(index,:)|.