Navigation

Operators and Keywords

Function List:

C++ API

: [s, i] = sort (x)
: [s, i] = sort (x, dim)
: [s, i] = sort (x, mode)
: [s, i] = sort (x, dim, mode)

Return a copy of x with the elements arranged in increasing order.

For matrices, sort orders the elements within columns

For example:

sort ([1, 2; 2, 3; 3, 1])
  ⇒  1  1
      2  2
      3  3

If the optional argument dim is given, then the matrix is sorted along the dimension defined by dim. The optional argument mode defines the order in which the values will be sorted. Valid values of mode are "ascend" or "descend".

The sort function may also be used to produce a matrix containing the original row indices of the elements in the sorted matrix. For example:

[s, i] = sort ([1, 2; 2, 3; 3, 1])
 ⇒ s = 1  1
        2  2
        3  3
 ⇒ i = 1  3
        2  1
        3  2

For equal elements, the indices are such that equal elements are listed in the order in which they appeared in the original list.

Sorting of complex entries is done first by magnitude (abs (z)) and for any ties by phase angle (angle (z)). For example:

sort ([1+i; 1; 1-i])
   ⇒ 1 + 0i
      1 - 1i
      1 + 1i

NaN values are treated as being greater than any other value and are sorted to the end of the list.

The sort function may also be used to sort strings and cell arrays of strings, in which case ASCII dictionary order (uppercase ’A’ precedes lowercase ’a’) of the strings is used.

The algorithm used in sort is optimized for the sorting of partially ordered lists.

See also: sortrows, issorted.

Package: octave