MATLAB Function Reference Previous page   Next Page
sort

Sort array elements in ascending or descending order

Syntax

Description

B = sort(A) sorts the elements along different dimensions of an array, and arranges those elements in ascending order.

If A is a ...
sort(A) ...
Vector
Sorts the elements of A.
Matrix
Sorts each column of A.
Multidimensional array
Sorts A along the first non-singleton dimension, and returns an array of sorted vectors.
Cell array of strings
Sorts the strings in ASCII dictionary order.

Integer, real, logical, and character arrays are permitted. Floating-point arrays can be complex. For elements of A with identical values, the order of these elements is preserved in the sorted list. When A is complex, the elements are sorted by magnitude, i.e., abs(A), and where magnitudes are equal, further sorted by phase angle, i.e., angle(A), on the interval . If A includes any NaN elements, sort places these at the high end.

B = sort(A,dim) sorts the elements along the dimension of A specified by a scalar dim.

B = sort(...,mode) sorts the elements in the specified direction, depending on the value of mode.

'ascend'
Ascending order (default)
'descend'
Descending order

[B,IX] = sort(A,...) also returns an array of indices IX, where size(IX) == size(A). If A is a vector, B = A(IX). If A is an m-by-n matrix, then each column of IX is a permutation vector of the corresponding column of A, such that

If A has repeated elements of equal value, the returned indices preserve the original ordering.

Sorting Complex Entries

If A has complex entries r and s, sort orders them according to the following rule: r appears before s in sort(A) if either of the following hold:

For example,

Examples

Example 1. This example sorts a matrix A in each dimension, and then sorts it a third time, requesting an array of indices for the sorted result.

Example 2. This example sorts each column of a matrix in descending order.

This is equivalent to

See Also

issorted, max, mean, median, min, sortrows


Previous page  smooth3 sortrows Next page

© 1994-2005 The MathWorks, Inc.