# sort

## Purpose

Sort elements in ascending order.

## Synopsis

    Y = sort(X)
    [Y,I] = sort(X)

## Description

`sort(X)`, where `X` is a matrix of real values, sorts each column of `X` in ascending order. If `X` is a vector of real values, `sort` sorts the elements of `X` in ascending order. `NaN`s appear at the end of the sorted list, after the highest integers. For identical values in `X`, the location in the input vector or matrix determines location in the sorted list.

`sort` orders complex input according to magnitude. Again, `NaN`s are appear at the end of the sorted list. For identical values, the phase of the input value on the interval [-`pi pi`] determines the final location. (A value that occurs directly on the negative real axis has phase -`pi`.) If the phase of the values is equal, `sort` uses location in the input vector or matrix to determine location in the sorted list.

`[Y,I] = sort(X)`, where `X` is a matrix, also returns an `m`-by-`n` index matrix `I`, with each column a permutation of `1:m`, so that for `j = 1:n`, `Y(:,j)` `=` `X(I(:,j),j)`. If `X` is a vector, `I` is an index vector, a permutation of `1:n`, so that `Y = X(I)`.

If `X` has repeated elements of equal value, indices are returned that preserve the original relative ordering.

When `X` is complex, the elements are sorted by `abs(X)`.

## Examples

Let `X = magic(4)`

    X =
        16    2    3   13
         5   11   10    8
         9    7    6   12
         4   14   15    1

Then

    [Y,I] = sort(X)

produces

    Y =
         4    2    3    1
         5    7    6    8
         9   11   10   12
        16   14   15   13

     I =
         4    1    1    4
         2    3    3    2
         3    2    2    3
         1    4    4    1

## See Also

    find, max, mean, median, min

(c) Copyright 1994 by The MathWorks, Inc.