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, sortrows sorts according to the values in the next column and repeats this behavior for succeeding equal values.

example

B = sortrows(A,column) sorts A based on the columns specified in the vector column. 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.

example

B = sortrows(___,direction) sorts the rows of A in the order specified by direction 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.

example

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

example

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

example

tblB = sortrows(tblA) sorts the rows of a table in ascending order based on the values in the first variable. If elements in the first variable are repeated, then sortrows sorts by the elements in the second variable, and so on.

If tblA is a timetable, then sortrows sorts the rows of tblA in ascending order based on its row times. Row times of a timetable label the rows along the first dimension of the timetable.

example

tblB = sortrows(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, then sortrows returns tblA.

This syntax is not supported when tblA is a timetable.

example

tblB = sortrows(tblA,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.

example

tblB = sortrows(tblA,vars) sorts a table by the elements in the variables specified by vars. For example, sortrows(tblA,{'Var1','Var2'}) first sorts the rows of tblA based on the elements in Var1, then by the elements in Var2.

• If tblA is a table and it has row names, then vars can include the row names.

• If tblA is a timetable, then vars can include the row times.

example

tblB = sortrows(___,direction) sorts tblA in the order specified by direction 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.

example

tblB = 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 in Var1, ordering missing elements such as NaN at the beginning of the table.

example

[tblB,index] = sortrows(___) also returns an index vector such that tblB = 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, 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 = sortrows(A)
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 = sortrows(A,2)
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 = sortrows(A,[1 7])
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

index = 6×1

2
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 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 = sortrows(A)
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

angle(A(1,1))
ans = 1.1071
angle(A(3,1))
ans = 0.4636

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

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)
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 = sortrows(tblA)
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

index = 5×1

5
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)
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

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 a 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 or cell array of character vectors containing 'ascend' (default) 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 the direction argument are specified together, then sortrows sorts according to direction, ignoring the signs of the elements in column.

Data Types: char | string | cell

Input table, specified as a table or a timetable. Each variable in tblA must be a valid input to sort or sortrows.

Data Types: table | timetable

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

• If tblA is a table with row names, then rowDimName 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 of tblA using tblA.Properties.DimensionNames.

• If tblA is a timetable, then rowDimName is the name of the vector of row times. You can specify its name when you create a timetable, such as Time or Date. You can also access the dimension names using tblA.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 named Date, then sortrows(TT,'Date') sorts the timetable on the dates and times that Date contains.

Data Types: char

Sorting variables, specified as a scalar integer, a vector of integers, a variable name, a cell array of variable names, or a logical vector. vars indicates the table variables to sort by.

If an element of vars is a positive integer, then sortrows sorts the corresponding variable in tblA in ascending order. If an element of vars is a negative integer, then sortrows sorts the corresponding variable in tblA in descending order.

Example: sortrows(tblA,{'Height','Weight'}) sorts the rows of tblA in ascending order, first by the variable Height, then by the variable Weight to break ties.

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 | char | string | cell | logical

Name-Value Arguments

Specify optional comma-separated pairs of Name,Value arguments. Name is the argument name and Value is the corresponding value. Name must appear inside quotes. You can specify several name and value pair arguments in any order as Name1,Value1,...,NameN,ValueN.

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

Placement of missing values (NaN, NaT, <undefined>, and missing) 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 of A by real(A) when A is real, and sort by abs(A) when A is complex.

• 'real' — Sort rows of A by real(A) when A is real or complex. If a column of A has elements with equal real parts, then use imag(A) to break ties.

• 'abs' — Sort rows of A by abs(A) when A is real or complex. If a column of A has elements with equal magnitude, then use angle(A) in the interval (-π,π] to break ties.

Output Arguments

collapse all

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

Sorted table, returned as a table or timetable with the same variables as tblA.

Data Types: table | timetable

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

Data Types: double