| MATLAB Function Reference | ![]() |
B = sortrows(A)
B = sortrows(A,column)
[B,index] = sortrows(A,...)
B = sortrows(A) sorts the rows of A in ascending order. Argument A must be either a matrix or a column vector.
For strings, this is the familiar dictionary sort. When A is complex, the elements are sorted by magnitude, and,
where magnitudes are equal, further sorted by phase angle on the interval
.
B = sortrows(A,column) sorts the matrix based on the columns specified in the vector column. If an element of column is positive, the MATLAB® software sorts the corresponding column of matrix A in ascending order; if an element of column is negative, MATLAB sorts the corresponding column in descending order. For example, sortrows(A,[2 -3]) sorts the rows of A first in ascending order for the second column, and then by descending order for the third column.
[B,index] = sortrows(A,...) also returns an index vector index.
If A is a column vector, then B = A(index). If A is an m-by-n matrix, then B = A(index,:).
Start with a mostly random matrix, A:
rand('state',0)
A = floor(rand(6,7) * 100);
A(1:4,1)=95; A(5:6,1)=76; A(2:4,2)=7; A(3,3)=73
A =
95 45 92 41 13 1 84
95 7 73 89 20 74 52
95 7 73 5 19 44 20
95 7 40 35 60 93 67
76 61 93 81 27 46 83
76 79 91 0 19 41 1When 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):
sortrows(A)
ans =
76 61 93 81 27 46 83
76 79 91 0 19 41 1
95 7 40 35 60 93 67
95 7 73 5 19 44 20
95 7 73 89 20 74 52
95 45 92 41 13 1 84When called with two input arguments, sortrows bases the sort entirely on the column specified in the second argument. Rows that have equal elements in this column are sorted; rows with equal elements in other columns are left in their original order:
sortrows(A,1)
ans =
76 61 93 81 27 46 83
76 79 91 0 19 41 1
95 45 92 41 13 1 84
95 7 73 89 20 74 52
95 7 73 5 19 44 20
95 7 40 35 60 93 67This example specifies two columns to sort by: columns 1 and 7. This tells sortrows to sort by column 1 first, and then for any rows with equal values in column 1, to sort by column 7:
sortrows(A,[1 7])
ans =
76 79 91 0 19 41 1
76 61 93 81 27 46 83
95 7 73 5 19 44 20
95 7 73 89 20 74 52
95 7 40 35 60 93 67
95 45 92 41 13 1 84Sort the matrix using the values in column 4 this time and in reverse order:
sortrows(A, -4)
ans =
95 7 73 89 20 74 52
76 61 93 81 27 46 83
95 45 92 41 13 1 84
95 7 40 35 60 93 67
95 7 73 5 19 44 20
76 79 91 0 19 41 1![]() | sort | sound | ![]() |
| © 1984-2008- The MathWorks, Inc. - Site Help - Patents - Trademarks - Privacy Policy - Preventing Piracy - RSS |