Matlab sort function to sort a two-dimensional array2008-09-14 22:51In Matlab sort a vector (one-dimensional), you can use sort (A), where A is the vector to be sorted, if only used to sort A, then directly use sort (A) can be used, if you also need to sort the original index can be retained with the return value, that is, [B,ind]. If you still need to keep the original index after sorting, you can use the return value, that is, [B,ind]=sort(A), after the calculation, B is the vector after sorting A, A remains unchanged, and ind is the index of each item in B corresponding to the item in A. The sorting is done in an ascending order.
In Matlab, to access the elements of a matrix, the first element of the vector A is accessed in one dimension with A(1); (subscripts start at 1); and the elements of the first row and second column of A are accessed in two dimensions with A(1, 2).
Since in the result of the sort function, is an ascending order, to convert to descending order, first use X = eye (n) to generate an n-dimensional unit array, and then use X = rot90 (X) will be rotated into a sub-diagonal unit array, and then multiply the original matrix by X can be, such as to speak of the A inverse order using the following steps:
X=eye(size(A ));
X=rot90(X);
A=A*X;
If a is a 2*n matrix, i.e. two rows.
b=a(1,:);
[c,pos]=sort(b);%pos is the sorted subscript, c is the result of the first row;
a(2,:)=a(2,pos);%The second row corresponds to the subscript of the first row
a(1,:)=c;%The result of the first row is re-assigned to a. first row
The following applies to m*n matrices sorted by the first row
[ b, pos ] = sort( a( 1, : ) );
a = a( :, pos );