sortrows - Sort rows of matrix or table - MATLAB (original) (raw)
Sort rows of matrix or table
Syntax
Description
Array Data
[B](#bt8bwzx-1-B) = sortrows([A](#bt8bwzx-1-A))
sorts the rows of an array based on the elements in the first column. By default, sortrows
uses ascending sorted order. When the first column contains repeated elements, sortrows
sorts according to the values in the next column and repeats this behavior for succeeding equal values.
[B](#bt8bwzx-1-B) = sortrows([A](#bt8bwzx-1-A),[column](#bt8bwzx-1-column))
specifies the columns by which to sort the rows. For example,sortrows(A,[4 6])
first sorts the rows ofA
based on elements in the fourth column, then based on elements in the sixth column to break ties.
[B](#bt8bwzx-1-B) = sortrows([A](#bt8bwzx-1-A),___,[direction](#bt8bwzx-1-direction))
specifies the sorting direction for any of the previous syntaxes. For example,sortrows(A,'descend')
uses descending sorting order.
[B](#bt8bwzx-1-B) = sortrows([A](#bt8bwzx-1-A),___,[Name,Value](#namevaluepairarguments))
specifies additional parameters for sorting rows. For example,sortrows(A,'ComparisonMethod','abs')
sorts the elements in A
by magnitude.
[[B](#bt8bwzx-1-B),[index](#bt8bwzx-1-index)] = sortrows([A](#bt8bwzx-1-A),___)
also returns an index vector that describes the rearrangement of rows such that B = A(index,:)
.
Table Data
[tblB](#bt8bwzx-1-tblB) = sortrows([tblA](#bt8bwzx-1-tblA))
sorts the rows of a table or timetable.
- If
tblA
is a table, thensortrows
sortstblA
in ascending order based on the values in the first variable. If elements in the first variable are repeated, thensortrows
sorts by the elements in the second variable, and so on. - If
tblA
is a timetable, thensortrows
sorts the rows oftblA
in ascending order based on its row times. However, the rows are sorted only with respect to the row times. If row times are repeated, thensortrows
does not sort by the elements in the timetable variables.
[tblB](#bt8bwzx-1-tblB) = sortrows([tblA](#bt8bwzx-1-tblA),'RowNames')
sorts a table based on its row names. Row names of a table label the rows along the first dimension of the table. If tblA
does not have row names, that is, if tblA.Properties.RowNames
is empty, thensortrows
returns tblA
.
This syntax is not supported when tblA
is a timetable.
[tblB](#bt8bwzx-1-tblB) = sortrows([tblA](#bt8bwzx-1-tblA),[rowDimName](#bt8bwzx-1-rowDimName))
sorts based on row labels along the first dimension.
- If
tblA
is a table, then row labels are row names. - If
tblA
is a timetable, then row labels are row times.
[tblB](#bt8bwzx-1-tblB) = sortrows([tblA](#bt8bwzx-1-tblA),[vars](#bt8bwzx-1-vars))
sorts based on the specified table variables. For example,sortrows(tblA,{'Var1','Var2'})
first sorts the rows oftblA
based on the elements in Var1
, then by the elements in Var2
.
- If
tblA
is a table and it has row names, thenvars
can include the row names. - If
tblA
is a timetable, thenvars
can include the row times.
[tblB](#bt8bwzx-1-tblB) = sortrows([tblA](#bt8bwzx-1-tblA),___,[direction](#bt8bwzx-1-direction))
sorts the rows in tblA
in specified direction for any of the previous table syntaxes.
[tblB](#bt8bwzx-1-tblB) = sortrows([tblA](#bt8bwzx-1-tblA),___,[Name,Value](#namevaluepairarguments))
specifies additional parameters for sorting rows of a table or timetable. For example, sortrows(tblA,'Var1','MissingPlacement','first')
sorts based on the elements in Var1
, ordering missing elements such as NaN
at the beginning of the table.
[[tblB](#bt8bwzx-1-tblB),[index](#bt8bwzx-1-index)] = sortrows([tblA](#bt8bwzx-1-tblA),___)
also returns an index vector such that tblB = tblA(index,:)
.
Examples
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
A = 6×7
95 27 95 79 67 70 69
95 7 48 95 75 3 31
95 7 48 65 74 27 95
95 7 14 3 39 4 3
76 15 42 84 65 9 43
76 97 91 93 17 82 38
B = 6×7
76 15 42 84 65 9 43
76 97 91 93 17 82 38
95 7 14 3 39 4 3
95 7 48 65 74 27 95
95 7 48 95 75 3 31
95 27 95 79 67 70 69
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 = 6×7
95 7 48 95 75 3 31
95 7 48 65 74 27 95
95 7 14 3 39 4 3
76 15 42 84 65 9 43
95 27 95 79 67 70 69
76 97 91 93 17 82 38
Sort the rows of A
based on the elements in the first column, and look to the seventh column to break any ties.
D = 6×7
76 97 91 93 17 82 38
76 15 42 84 65 9 43
95 7 14 3 39 4 3
95 7 48 95 75 3 31
95 27 95 79 67 70 69
95 7 48 65 74 27 95
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')
E = 6×7
95 7 48 95 75 3 31
76 97 91 93 17 82 38
76 15 42 84 65 9 43
95 27 95 79 67 70 69
95 7 48 65 74 27 95
95 7 14 3 39 4 3
Create a matrix containing complex numbers, and sort the rows of the matrix in ascending order based on the elements in the first column. Since the magnitudes of A(1,1)
and A(3,1)
are equal, sortrows
computes their angles to break the tie.
A = [1+2i 3+i i; 2+10i 6i 2+5i; 2+i 4 3+3i]
A = 3×3 complex
1.0000 + 2.0000i 3.0000 + 1.0000i 0.0000 + 1.0000i 2.0000 +10.0000i 0.0000 + 6.0000i 2.0000 + 5.0000i 2.0000 + 1.0000i 4.0000 + 0.0000i 3.0000 + 3.0000i
B = 3×3 complex
2.0000 + 1.0000i 4.0000 + 0.0000i 3.0000 + 3.0000i 1.0000 + 2.0000i 3.0000 + 1.0000i 0.0000 + 1.0000i 2.0000 +10.0000i 0.0000 + 6.0000i 2.0000 + 5.0000i
Use the 'real'
option to sort the rows of A
by their real part. Since A(2,1)
and A(3,1)
have equal real parts, sortrows
uses the imaginary part to break the tie.
C = sortrows(A,'ComparisonMethod','real')
C = 3×3 complex
1.0000 + 2.0000i 3.0000 + 1.0000i 0.0000 + 1.0000i 2.0000 + 1.0000i 4.0000 + 0.0000i 3.0000 + 3.0000i 2.0000 +10.0000i 0.0000 + 6.0000i 2.0000 + 5.0000i
Create a 6-by-2 string array. Sort its rows in ascending alphabetical order based on the elements in the first column. When the first column contains repeated elements, use the second column to break the tie.
A = ["B" "Y"; "B" "Z"; "A" "Z"; ... "B" "X"; "A" "Y"; "A" "X"]; B1 = sortrows(A)
B1 = 6×2 string "A" "X" "A" "Y" "A" "Z" "B" "X" "B" "Y" "B" "Z"
Sort the rows again. This time, break the tie for elements in the first column by sorting the elements in the second column in descending alphabetical order.
B2 = sortrows(A,[1 2],["ascend" "descend"])
B2 = 6×2 string "A" "Z" "A" "Y" "A" "X" "B" "Z" "B" "Y" "B" "X"
Sort the rows of a table by variable values.
Create a table with four variables listing patient information for five people.
LastName = {'Smith';'Johnson';'Williams';'Jones';'Brown'}; Age = [38;43;38;40;49]; Height = [71;69;64;67;64]; Weight = [176;163;131;133;119]; BloodPressure = [124 93; 109 77; 125 83; 117 75; 122 80];
tblA = table(Age,Height,Weight,BloodPressure,'RowNames',LastName)
tblA=5×4 table Age Height Weight BloodPressure ___ ______ ______ _____________
Smith 38 71 176 124 93
Johnson 43 69 163 109 77
Williams 38 64 131 125 83
Jones 40 67 133 117 75
Brown 49 64 119 122 80
Sort the rows of the table. The sortrows
function sorts the rows in ascending order first by the variable Age
, and then by the variable Height
to break the tie between the two rows with equal ages.
tblB=5×4 table Age Height Weight BloodPressure ___ ______ ______ _____________
Williams 38 64 131 125 83
Smith 38 71 176 124 93
Jones 40 67 133 117 75
Johnson 43 69 163 109 77
Brown 49 64 119 122 80
Create a table with four variables listing patient information for five people.
LastName = {'Smith';'Johnson';'Williams';'Jones';'Brown'}; Age = [38;43;38;40;49]; Height = [71;69;64;67;64]; Weight = [176;163;131;133;119]; BloodPressure = [124 93; 109 77; 125 83; 117 75; 122 80];
tblA = table(Age,Height,Weight,BloodPressure,'RowNames',LastName)
tblA=5×4 table Age Height Weight BloodPressure ___ ______ ______ _____________
Smith 38 71 176 124 93
Johnson 43 69 163 109 77
Williams 38 64 131 125 83
Jones 40 67 133 117 75
Brown 49 64 119 122 80
Sort the rows of the table in ascending order based on the row names, and return the index vector that describes how the rows were rearranged.
[tblB,index] = sortrows(tblA,'RowNames')
tblB=5×4 table Age Height Weight BloodPressure ___ ______ ______ _____________
Brown 49 64 119 122 80
Johnson 43 69 163 109 77
Jones 40 67 133 117 75
Smith 38 71 176 124 93
Williams 38 64 131 125 83
Create a table with four variables listing patient information for five people.
LastName = {'Sweet';'Jacobson';'Wang';'Joiner';'Berger'}; Age = [38;43;38;40;49]; Height = [71;69;64;67;64]; Weight = [176;163;131;133;119]; BloodPressure = [124 93; 109 77; 125 83; 117 75; 122 80];
tblA = table(Age,Height,Weight,BloodPressure,'RowNames',LastName)
tblA=5×4 table Age Height Weight BloodPressure ___ ______ ______ _____________
Sweet 38 71 176 124 93
Jacobson 43 69 163 109 77
Wang 38 64 131 125 83
Joiner 40 67 133 117 75
Berger 49 64 119 122 80
Sort the rows of the table in ascending order by Height
, and then in descending order by Weight
.
tblB = sortrows(tblA,{'Height','Weight'},{'ascend','descend'})
tblB=5×4 table Age Height Weight BloodPressure ___ ______ ______ _____________
Wang 38 64 131 125 83
Berger 49 64 119 122 80
Joiner 40 67 133 117 75
Jacobson 43 69 163 109 77
Sweet 38 71 176 124 93
Create a table with four variables listing patient information for five people. The Weight
variable contains missing values.
LastName = {'Sweet';'Jacobson';'Wang';'Joiner';'Berger'}; Age = [38;43;38;40;49]; Height = [71;69;64;67;64]; Weight = [176;NaN;131;133;NaN]; BloodPressure = [124 93; 109 77; 125 83; 117 75; 122 80]; tblA = table(Age,Height,Weight,BloodPressure,'RowNames',LastName)
tblA=5×4 table Age Height Weight BloodPressure ___ ______ ______ _____________
Sweet 38 71 176 124 93
Jacobson 43 69 NaN 109 77
Wang 38 64 131 125 83
Joiner 40 67 133 117 75
Berger 49 64 NaN 122 80
Sort the rows of the table in ascending order by Weight
, placing the rows containing NaN
first.
tblB = sortrows(tblA,'Weight','MissingPlacement','first')
tblB=5×4 table Age Height Weight BloodPressure ___ ______ ______ _____________
Jacobson 43 69 NaN 109 77
Berger 49 64 NaN 122 80
Wang 38 64 131 125 83
Joiner 40 67 133 117 75
Sweet 38 71 176 124 93
Create a timetable, and sort the rows by row times.
TimeDuration = [hours(3) hours(2) hours(1) hours(5) hours(6)]'; TT = timetable(TimeDuration,[98;97.5;97.9;98.1;101],[120;111;119;117;118]);
B = sortrows(TT,'TimeDuration')
B=5×2 timetable TimeDuration Var1 Var2 ____________ ____ ____
1 hr 97.9 119
2 hr 97.5 111
3 hr 98 120
5 hr 98.1 117
6 hr 101 118
Input Arguments
Input array, specified as a column vector or matrix.
Data Types: double
| single
| int8
| int16
| int32
| int64
| uint8
| uint16
| uint32
| uint64
| logical
| char
| string
| cell
| categorical
| datetime
| duration
Complex Number Support: Yes
Column sorting vector, specified as a nonzero integer scalar or vector of nonzero integers. Each specified integer value indicates a column to sort by. Negative integers indicate that the sort order is descending.
Sorting direction, specified as either 'ascend'
,'descend'
, or a string array or cell array of character vectors that specifies some combination of these values.
If direction
is 'ascend'
or'descend'
, then the sorting direction applies for all column sorting vectors or sorting variables. If direction
is a string array or cell array of character vectors, then each entry corresponds to a column sorting vector or a sorting variable.
If you specify both column
anddirection
, then the direction
determines the sorting direction and sortrows
ignores the signs of the elements in column
.
Example: sortrows(X,[2 3],{'ascend' 'descend'})
first sorts rows in ascending order according to column 2 of X
. Then, rows with equal entries in column 2 are sorted in descending order according to column 3.
Input table, specified as a table or timetable. Each variable intblA
must be a valid input tosort
or sortrows
.
Name of the first dimension of the input table or timetable, specified as a string scalar or character vector.
- If
tblA
is a table with row names, thenrowDimName
is the name of the first dimension of the table. By default, the name of the first dimension is"Row"
. Dimension names are a property of tables. You can access the dimension names oftblA
usingtblA.Properties.DimensionNames
. - If
tblA
is a timetable, thenrowDimName
is the name of the vector of row times. You can specify its name when you create a timetable, such asTime
orDate
. You can also access the dimension names usingtblA.Properties.DimensionNames
.
Example: If a table T
has row names, and you changed the name of the first dimension using T.Properties.DimensionName{1} = "Name"
, then sortrows(T,"Name")
sorts the table by row name.
Example: If a timetable TT
has a time vector namedDate
, then sortrows(TT,"Date")
sorts the timetable on the dates and times that Date
contains.
Data Types: string
| char
Sorting variables, specified as a scalar integer, vector of integers, variable name, string array of variable names, cell array of variable names,pattern scalar, or logical vector. vars
indicates the table variables to sort by.
If you do not specify the direction
argument, the sign of the elements in vars
determines the sorting direction of the variables. If an element is a positive integer, thensortrows
sorts the corresponding variable intblA
in ascending order. If an element is a negative integer, then sortrows
sorts the corresponding variable in tblA
in descending order. Otherwise, if you specify the direction
argument, sortrows
ignores the sign of vars
and sorts the specified variables according to direction
.
Example: sortrows(tblA,["Height","Weight"])
sorts the rows of tblA
in ascending order, first by the variableHeight
, then by the variableWeight
to break ties.
Example: sortrows(tblA,"X" + wildcardPattern)
sorts the rows of tblA
are in ascending order by the table variables whose names begin with the letter "X"
, using a wildcard pattern to match the remaining letters in their names.
Example: sortrows(tblA,[1 4])
sorts by the first variable of tblA
in ascending order, then sorts by the fourth variable to break ties.
Example: sortrows(TT,["Time","X"])
sorts the row times of timetable TT
in ascending order first, then sorts by the table variable X
to break ties.
Data Types: double
| single
| string
| char
| cell
| pattern
| logical
Name-Value Arguments
Specify optional pairs of arguments asName1=Value1,...,NameN=ValueN
, where Name
is the argument name and Value
is the corresponding value. Name-value arguments must appear after other arguments, but the order of the pairs does not matter.
Before R2021a, use commas to separate each name and value, and enclose Name
in quotes.
Example: sortrows(A,'MissingPlacement','last')
Placement of missing values (NaN
,NaT
, <undefined>
, andmissing
) specified as the comma-separated pair consisting of 'MissingPlacement'
and one of the following:
'auto'
— Missing elements are placed last for ascending order and first for descending order.'first'
— Missing elements are placed first.'last'
— Missing elements are placed last.
Element comparison method for numeric input, specified as'ComparisonMethod'
and one of these values:
'auto'
— Sort rows ofA
byreal(A)
whenA
is real, and sort byabs(A)
whenA
is complex.'real'
— Sort rows ofA
byreal(A)
whenA
is real or complex. If a column ofA
has elements with equal real parts, then useimag(A)
to break ties.'abs'
— Sort rows ofA
byabs(A)
whenA
is real or complex. If a column ofA
has elements with equal magnitude, then useangle(A)
in the interval (-π,π] to break ties.
Output Arguments
Sorted array, returned as a column vector or matrix. B
is the same size as A
.
Data Types: double
| single
| int8
| int16
| int32
| int64
| uint8
| uint16
| uint32
| uint64
| logical
| char
| string
| cell
| categorical
| datetime
| duration
Sorted table, returned as a table or timetable with the same variables astblA
.
Sort index, returned as a column vector. The sort index describes the rearrangement of the rows in the input such that B = A(index,:)
.
The sortrows
function uses a stable sorting algorithm. So, when the input contains repeated values, the sort index preserves the original order from the input, regardless of sorting direction. For example, if A = [1 1; 2 2; 1 2; 2 2]
, then [Ba,Ia] = sortrows(A,'ascend')
returns the sort index Ia = [1; 3; 2; 4]
and [Bd,Id] = sortrows(A,'descend')
returns the sort index Id = [2; 4; 3; 1]
.
Data Types: double
Extended Capabilities
Thesortrows
function supports tall arrays with the following usage notes and limitations:
- Sorting by row names is not supported.
For more information, see Tall Arrays.
Usage notes and limitations:
- Cell or string input array is not supported.
- If
A
is complex with all zero imaginary parts, then MATLAB® might convertA
toreal(A)
before callingsortrows(A)
. In this case, MATLAB sorts the rows ofA
byreal(A)
, but the generated code sorts the rows ofA
byabs(A)
. To make the generated code match MATLAB, usesortrows(real(A))
orsortrows(A,'ComparisonMethod','real')
. See Code Generation for Complex Data with Zero-Valued Imaginary Parts (MATLAB Coder). - If
tblA
is a table or timetable, then the input argumentvars
must be constant. - If
tblA
is a table or timetable, and it has a variable that is a cell array of character vectors with multiple columns, then you cannot sorttblA
using the values in that variable. - The
vars
input argument does not support pattern expressions.
Usage notes and limitations:
- The first input argument must not be a cell array.
- If
A
is complex with all zero imaginary parts, then MATLAB might convertA
toreal(A)
before callingsortrows(A)
. In this case, MATLAB sorts the rows ofA
byreal(A)
, but the generated code sorts the rows ofA
byabs(A)
. To make the generated code match MATLAB, usesortrows(real(A))
orsortrows(A,'ComparisonMethod','real')
.
The sortrows
function supports GPU array input with these usage notes and limitations:
- Sorting cell arrays is not supported.
- Sparse inputs are not supported.
For more information, see Run MATLAB Functions on a GPU (Parallel Computing Toolbox).
Usage notes and limitations:
- Sorting cell arrays is not supported.
- Table, timetable, datetime and duration inputs are not supported.
For more information, see Run MATLAB Functions with Distributed Arrays (Parallel Computing Toolbox).
Version History
Introduced before R2006a