sortrows

Sorts the rows of a matrix or table by one or more columns.

Category: Language Fundamentals > Matrices and Arrays

Syntax

B = sortrows(A)

Sorts rows in ascending order, using the first column as the main key and the next ones to break ties.

B = sortrows(A, col)

Sorts by the columns listed in col. A negative number sorts that column in descending order.

B = sortrows(A, col, direction)

Applies 'ascend' or 'descend' to the chosen columns.

[B, I] = sortrows(___)

Also returns the row permutation.

Description

Rows are compared lexicographically: the first key column decides, and later columns are consulted only when earlier ones are equal. The sort is stable, so rows that tie on every key keep their original relative order.

Use the second output to apply the same reordering to other arrays, for example names(I).

Input arguments

A
Numeric matrix, table, cell array of character vectors or string array.
col
Vector of column indices. The sign gives the direction for each column.
direction
'ascend' (default) or 'descend'.

Output arguments

B
A with its rows reordered. Each row stays intact.
I
Index vector such that B = A(I,:).

Example

Sorting by one or two keys

A = [3 1; 1 2; 1 1; 2 9];
sortrows(A)
[B, I] = sortrows(A, [1 -2]);
B
I'
Output
ans = 4×2

     1     1
     1     2
     2     9
     3     1
B = 4×2

     1     2
     1     1
     2     9
     3     1
ans = 1×4

     2     3     4     1

See also

sort issorted unique table