## Documentation Center |

Sort elements of symbolic vectors or matrices

` Y = sort(X)` sorts
the elements of a symbolic vector or matrix in ascending order. If

`[ Y,I] =
sort(___)` shows the indices that each element
of

If `X` is an `m`-by-`n` matrix
and you sort elements of each column (`dim`` =
2`), then each column of `I` is a permutation
vector of the corresponding column of `X`, such
that

for j = 1:n Y(:,j) = X(I(:,j),j); end

If `X` is a two-dimensional matrix, and
you sort the elements of each column, the array `I` shows
the row indices that the elements of `Y` had in
the original matrix `X`. If you sort the elements
of each row, `I` shows the original column indices.

By default, `sort` sorts
the element of a vector or a matrix in ascending order.

Sort the elements of the following symbolic vector:

syms a b c d e sort([7 e 1 c 5 d a b])

ans = [ 1, 5, 7, a, b, c, d, e]

To find the indices that each element of a
new vector or matrix `Y` had in the original vector
or matrix `X`, call `sort` with
two output arguments.

Sort the matrix `X` returning the matrix of
indices that each element of the sorted matrix had in `X`:

X = sym(magic(3)); [Y, I] = sort(X)

Y = [ 3, 1, 2] [ 4, 5, 6] [ 8, 9, 7] I = 2 1 3 3 2 1 1 3 2

When sorting elements of a matrix, `sort` can
work along the columns or rows of that matrix.

Sort the elements of the following symbolic matrix:

X = sym(magic(3))

X = [ 8, 1, 6] [ 3, 5, 7] [ 4, 9, 2]

By default, the `sort` command sorts elements
of each column:

sort(X)

ans = [ 3, 1, 2] [ 4, 5, 6] [ 8, 9, 7]

To sort the elements of each row, use set the value of the `dim` option
to `2`:

sort(X,2)

ans = [ 1, 6, 8] [ 3, 5, 7] [ 2, 4, 9]

`sort` can sort the elements
of a vector or a matrix in descending order.

Sort the elements of this vector in descending order:

syms a b c d e sort([7 e 1 c 5 d a b], 'descend')

ans = [ e, d, c, b, a, 7, 5, 1]

Sort the elements of each column of this matrix `X` in
descending order:

X = sym(magic(3)) sort(X,'descend')

X = [ 8, 1, 6] [ 3, 5, 7] [ 4, 9, 2] ans = [ 8, 9, 7] [ 4, 5, 6] [ 3, 1, 2]

Now, sort the elements of each row of `X` in
descending order:

sort(X, 2, 'descend')

ans = [ 8, 6, 1] [ 7, 5, 3] [ 9, 4, 2]

Was this topic helpful?