sortrows - Sort rows of matrix or table - MATLAB (original) (raw)
Sort rows of matrix or table
Syntax
Description
[B](#bt8bwzx-1-B) = sortrows([A](#bt8bwzx-1-A))
sorts the rows of A
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))
sorts A
based on the columns specified in the vectorcolumn
. For example, sortrows(A,4)
sorts the rows of A
in ascending order based on the elements in the fourth column. sortrows(A,[4 6])
first sorts the rows of A
based on the elements in the fourth column, then based on the elements in the sixth column to break ties.
[B](#bt8bwzx-1-B) = sortrows(___,[direction](#bt8bwzx-1-direction))
sorts the rows of A
in the order specified bydirection
for any of the previous syntaxes.direction
can be 'ascend'
(default) for ascending order or 'descend'
for descending order.direction
can also be a cell array whose elements are'ascend'
and 'descend'
, where each element corresponds to a column that sortrows
operates on. For example, sortrows(A,[4 6],{'ascend' 'descend'})
sorts the rows of A
in ascending order based on the fourth column, then in descending order based on the sixth column to break ties.
[B](#bt8bwzx-1-B) = sortrows(___,[Name,Value](#namevaluepairarguments))
specifies additional parameters for sorting rows. For example,sortrows(A,'ComparisonMethod','abs')
sorts the elements of A
by magnitude.
[[B](#bt8bwzx-1-B),[index](#bt8bwzx-1-index)] = sortrows(___)
also returns an index vector that describes the rearrangement of rows such that B = A(index,:)
.
[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.
Row times of a timetable aredatetime
orduration
values that label the rows along the first dimension of the timetable.
[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 tblA
by row labels rowDimName
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 a table by the elements in the variables specified byvars
. 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(___,[direction](#bt8bwzx-1-direction))
sorts tblA
in the order specified bydirection
for any of the previous table syntaxes.direction
can be 'ascend'
or'descend'
, which is applied to all specified variables, row names, or row times that sortrows
operates on.direction
can also be a cell array whose elements are'ascend'
and 'descend'
, where each element corresponds to the specified variables, row names, or row times being sorted on.
[tblB](#bt8bwzx-1-tblB) = sortrows(___,[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(___)
also returns an index vector such thattblB = tblA(index,:)
.
Examples
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
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
Complex Matrix
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
Sort Rows of Cell Array
Create a 6-by-2 cell array of character vectors, and sort its rows. The result is an alphabetized list sorted by both country and name.
A = {'Germany' 'Lukas'; 'USA' 'William'; 'USA' 'Andrew'; ... 'Germany' 'Andreas'; 'USA' 'Olivia'; 'Germany' 'Julia'}
A = 6x2 cell {'Germany'} {'Lukas' } {'USA' } {'William'} {'USA' } {'Andrew' } {'Germany'} {'Andreas'} {'USA' } {'Olivia' } {'Germany'} {'Julia' }
B = 6x2 cell {'Germany'} {'Andreas'} {'Germany'} {'Julia' } {'Germany'} {'Lukas' } {'USA' } {'Andrew' } {'USA' } {'Olivia' } {'USA' } {'William'}
Sort the countries first, then sort the names in descending order.
C = sortrows(A,[1 2],{'ascend' 'descend'})
C = 6x2 cell {'Germany'} {'Lukas' } {'Germany'} {'Julia' } {'Germany'} {'Andreas'} {'USA' } {'William'} {'USA' } {'Olivia' } {'USA' } {'Andrew' }
Sort Rows of Table
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
Sort Rows of Table by Row Names
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
Sort Rows of Table by Variables
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
Table with Missing Elements
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
Sort Rows of Timetable
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
A
— Input array
column vector | matrix
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
— Column sorting vector
nonzero integer scalar | vector of nonzero integers
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.
direction
— Sorting direction
'ascend'
(default) | 'descend'
Sorting direction, specified as a character vector, string array, or cell array of character vectors containing 'ascend'
or'descend'
.
If direction
is a cell array of character vectors, then the number of entries must match the number of columns or variables being sorted on.
If the column
argument and thedirection
argument are specified together, thensortrows
sorts according todirection
, ignoring the signs of the elements incolumn
. For 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.
Data Types: char
| string
| cell
tblA
— Input table
table | timetable
Input table, specified as a table or timetable. Each variable intblA
must be a valid input to sort
or sortrows
.
Data Types: table
| timetable
rowDimName
— Name of first dimension of input table or timetable
string scalar | character vector
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
vars
— Sorting variables
scalar integer | vector of integers | variable name | string array of variable names | cell array of variable names | pattern
scalar | logical vector
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')
MissingPlacement
— Placement of missing values
'auto'
(default) | 'first'
| '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.
ComparisonMethod
— Element comparison method
'auto'
(default) | 'real'
| 'abs'
Element comparison method for numeric input, specified as the comma-separated pair consisting of 'ComparisonMethod'
and one of the following:
'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
B
— Sorted array
vector | matrix | multidimensional array
Sorted array, returned as a vector, matrix, or multidimensional array.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
tblB
— Sorted table
table | timetable
Sorted table, returned as a table or timetable with the same variables astblA
.
Data Types: table
| timetable
index
— Sort index
index vector
Sort index, returned as an index 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
Tall Arrays
Calculate with arrays that have more rows than fit in memory.
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.
C/C++ Code Generation
Generate C and C++ code using MATLAB® Coder™.
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')
. 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.
GPU Code Generation
Generate CUDA® code for NVIDIA® GPUs using GPU Coder™.
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')
.
Thread-Based Environment
Run code in the background using MATLAB® backgroundPool
or accelerate code with Parallel Computing Toolbox™ ThreadPool
.
This function fully supports thread-based environments. For more information, see Run MATLAB Functions in Thread-Based Environment.
GPU Arrays
Accelerate code by running on a graphics processing unit (GPU) using Parallel Computing Toolbox™.
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).
Distributed Arrays
Partition large arrays across the combined memory of your cluster using 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