Main Content

sortrows

Sort rows of matrix or table

Description

example

B= sortrows(A)sorts the rows of a matrix in ascending order based on the elements in the first column. When the first column contains repeated elements,sortrowssorts according to the values in the next column and repeats this behavior for succeeding equal values.

example

B= sortrows(A,column)sortsAbased on the columns specified in the vectorcolumn. For example,sortrows(A,4)sorts the rows ofAin ascending order based on the elements in the fourth column.sortrows(A,[4 6])first sorts the rows ofAbased on the elements in the fourth column, then based on the elements in the sixth column to break ties.

example

B= sortrows(___,direction)sorts the rows ofAin the order specified bydirectionfor any of the previous syntaxes.directioncan be'ascend'(default) for ascending order or'descend'for descending order.directioncan also be a cell array whose elements are'ascend'and'descend', where each element corresponds to a column thatsortrowsoperates on. For example,sortrows(A,[4 6],{'ascend' 'descend'})sorts the rows ofAin ascending order based on the fourth column, then in descending order based on the sixth column to break ties.

example

B= sortrows(___,Name,Value)specifies additional parameters for sorting rows. For example,sortrows(A,'ComparisonMethod','abs')sorts the elements ofAby magnitude.

example

[B,index] = sortrows(___)also returns an index vector that describes the rearrangement of rows such thatB = A(index,:).

example

结核病lB= sortrows(结核病lA)sorts the rows of a table or timetable.

  • If结核病lAis a table, thensortrowssorts结核病lAin ascending order based on the values in the first variable. If elements in the first variable are repeated, thensortrowssorts by the elements in the second variable, and so on.

  • If结核病lAis a timetable, thensortrowssorts the rows of结核病lAin ascending order based on its row times. However, the rows are sorted only with respect to the row times. If row times are repeated, thensortrowsdoes not sort by the elements in the timetable variables.

    Row times of a timetable aredatetimeordurationvalues that label the rows along the first dimension of the timetable.

example

结核病lB= sortrows(结核病lA,'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结核病lAdoes not have row names, that is, if结核病lA.Properties.RowNamesis empty, thensortrowsreturns结核病lA.

This syntax is not supported when结核病lAis a timetable.

example

结核病lB= sortrows(结核病lA,rowDimName)sorts结核病lAby row labelsrowDimNamealong the first dimension.

  • If结核病lAis a table, then row labels are row names.

  • If结核病lAis a timetable, then row labels are row times.

example

结核病lB= sortrows(结核病lA,vars)sorts a table by the elements in the variables specified byvars. For example,sortrows(tblA,{'Var1','Var2'})first sorts the rows of结核病lAbased on the elements inVar1, then by the elements inVar2.

  • If结核病lAis a table and it has row names, thenvarscan include the row names.

  • If结核病lAis a timetable, thenvarscan include the row times.

example

结核病lB= sortrows(___,direction)sorts结核病lAin the order specified bydirectionfor any of the previous table syntaxes.directioncan be'ascend'or'descend', which is applied to all specified variables, row names, or row times thatsortrowsoperates on.directioncan 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.

example

结核病lB= sortrows(___,Name,Value)specifies additional parameters for sorting rows of a table or timetable. For example,sortrows(tblA,'Var1','MissingPlacement','first')sorts based on the elements inVar1, ordering missing elements such asNaNat the beginning of the table.

example

[结核病lB,index] = sortrows(___)also returns an index vector such that结核病lB = tblA(index,:).

Examples

collapse all

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,sortrowslooks to the elements in the second column to break the tie. For repeated elements in the second column,sortrowslooks to the third column, and so on.

rngdefault; 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×795 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 = sortrows(A)
B =6×776 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 ofAbased on the values in the second column. When the specified column has repeated elements, the corresponding rows maintain their original order.

C = sortrows(A,2)
C =6×795 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 ofAbased on the elements in the first column, and look to the seventh column to break any ties.

D = sortrows(A,[1 7])
D =6×776 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 ofAin descending order based on the elements in the fourth column, and display the output vectorindexto see how the rows were rearranged.

[E,index] = sortrows(A,4,'descend')
E =6×795 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
index =6×12 6 5 1 3 4

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 ofA(1,1)andA(3,1)are equal,sortrowscomputes 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 complex1.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 = sortrows(A)
B =3×3 complex2.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
angle(A(1,1))
ans = 1.1071
angle(A(3,1))
ans = 0.4636

Use the'real'option to sort the rows ofAby their real part. SinceA(2,1)andA(3,1)have equal real parts,sortrowsuses the imaginary part to break the tie.

C = sortrows(A,'ComparisonMethod','real')
C =3×3 complex1.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
imag(A(2,1))
ans = 10
imag(A(3,1))
ans = 1

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 = sortrows(A)
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 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)
结核病lA=5×4 tableAge 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. Thesortrowsfunction sorts the rows in ascending order first by the variableAge, and then by the variableHeightto break the tie between the two rows with equal ages.

结核病lB = sortrows(tblA)
结核病lB=5×4 tableAge 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)
结核病lA=5×4 tableAge 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')
结核病lB=5×4 tableAge 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
index =5×15 2 4 1 3

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)
结核病lA=5×4 tableAge 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 byHeight, and then in descending order byWeight.

结核病lB = sortrows(tblA,{'Height','Weight'},{'ascend','descend'})
结核病lB=5×4 tableAge 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. TheWeightvariable 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)
结核病lA=5×4 tableAge 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 byWeight, placing the rows containingNaNfirst.

结核病lB = sortrows(tblA,'Weight','MissingPlacement','first')
结核病lB=5×4 tableAge 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 timetableTimeDuration 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

collapse all

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 a character vector, string array, or cell array of character vectors containing'ascend'(default) or'descend'. Ifdirectionis a cell array of character vectors, then the number of entries must match the number of columns or variables being sorted on.

If thecolumnargument and thedirectionargument are specified together, thensortrowssorts according todirection, ignoring the signs of the elements incolumn.

Data Types:char|string|cell

Input table, specified as a table or timetable. Each variable in结核病lAmust be a valid input tosortorsortrows.

Data Types:table|timetable

Name of the first dimension of the input table or timetable, specified as a string scalar or character vector.

  • If结核病lAis a table with row names, thenrowDimNameis 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 of结核病lAusing结核病lA.Properties.DimensionNames.

  • If结核病lAis a timetable, thenrowDimNameis the name of the vector of row times. You can specify its name when you create a timetable, such asTimeorDate. You can also access the dimension names using结核病lA.Properties.DimensionNames.

Example:If a tableThas row names, and you changed the name of the first dimension usingT.Properties.DimensionName{1} = "Name", thensortrows(T,"Name")sorts the table by row name.

Example:If a timetableTThas a time vector namedDate, thensortrows(TT,"Date")sorts the timetable on the dates and times thatDatecontains.

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,patternscalar, or logical vector.varsindicates the table variables to sort by.

如果一个初步的ent ofvarsis a positive integer, thensortrowssorts the corresponding variable in结核病lAin ascending order. If an element ofvarsis a negative integer, thensortrowssorts the corresponding variable in结核病lAin descending order.

Example:sortrows(tblA,["Height","Weight"])sorts the rows of结核病lAin ascending order, first by the variableHeight, then by the variableWeightto break ties.

Example:sortrows(tblA,"X" + wildcardPattern)sorts the rows of结核病lAare in ascending order by the table variables whose names begin with the letter"X"剩下的,使用一个通配符模式匹配letters in their names.

Example:sortrows(tblA,[1 4])sorts by the first variable of结核病lAin ascending order, then sorts by the fourth variable to break ties.

Example:sortrows(TT,["Time","X"])sorts the row times of timetableTTin ascending order first, then sorts by the table variableXto break ties.

Data Types:double|single|string|char|cell|pattern|logical

Name-Value Arguments

Specify optional pairs of arguments asName1=Value1,...,NameN=ValueN, whereNameis the argument name andValueis 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 encloseNamein quotes.

Example:sortrows(A,'MissingPlacement','last')

Placement of missing values (NaN,NaT,, 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, specified as the comma-separated pair consisting of'ComparisonMethod'and one of the following:

  • 'auto'— Sort rows ofAbyreal(A)whenAis real, and sort byabs(A)whenAis complex.

  • 'real'— Sort rows ofAbyreal(A)whenAis real or complex. If a column ofAhas elements with equal real parts, then useimag(A)to break ties.

  • 'abs'— Sort rows ofAbyabs(A)whenAis real or complex. If a column ofAhas elements with equal magnitude, then useangle(A)in the interval (-π,π] to break ties.

Output Arguments

collapse all

Sorted array, returned as a vector, matrix, or multidimensional array.Bis the same size asA.

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 as结核病lA.

Data Types:table|timetable

Sort index, returned as an index vector. The sort index describes the rearrangement of the rows in the input such thatB = A(index,:).

Thesortrowsfunction 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, ifA = [1 1; 2 2; 1 2; 2 2], then[Ba,Ia] = sortrows(A,'ascend')returns the sort indexIa = [1; 3; 2; 4]and[Bd,Id] = sortrows(A,'descend')returns the sort indexId = [2; 4; 3; 1].

Data Types:double

Extended Capabilities

Version History

Introduced before R2006a

Baidu
map