sort

Sorts the elements of an array in ascending or descending order.

Category: Language Fundamentals > Matrices and Arrays

Syntax

B = sort(A)

Sorts ascending along the first non-singleton dimension.

B = sort(A, dim)

Sorts along dimension dim.

B = sort(___, direction)

'ascend' (default) or 'descend'.

[B, I] = sort(___)

Also returns the indices that map A to B.

Description

For a matrix, each column is sorted separately; use sort(A, 2) to sort each row. The sort is stable, so equal elements keep their original relative order, and I tells where each element came from. NaN values are placed last when ascending and first when descending. Complex numbers are ordered by magnitude, then by phase. Text is ordered by character code, so uppercase letters come before lowercase.

To sort whole rows by one column, use sortrows.

Input arguments

A
Numeric, logical, char, string, categorical or datetime array, or a cell array of character vectors.
dim
Dimension to sort along.
direction
'ascend' or 'descend'.

Output arguments

B
Sorted array, the same size as A.
I
Index array: B = A(I) for a vector.

Example

[s, i] = sort([3 1 2])
sort([3 1 2], 'descend')
sort([3 1; 2 5], 2)
sort({'pear', 'apple', 'fig'})
Output
s = 1×3

     1     2     3
i = 1×3

     2     3     1
ans = 1×3

     3     2     1
ans = 2×2

     1     3
     2     5
ans = 1×3 cell

    {'apple'}    {'fig'}    {'pear'}

See also

sortrows issorted max unique cummax