Sort elements of symbolic vectors or matrices
Y = sort(X)
[Y,I] = sort(___)
X is an
and you sort elements of each column (
2), then each column of
I is a permutation
vector of the corresponding column of
for j = 1:n Y(:,j) = X(I(:,j),j); end
X is a two-dimensional matrix, and
you sort the elements of each column, the array
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.
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
two output arguments.
Sort the matrix
X returning the matrix of
indices that each element of the sorted matrix had in
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,
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:
ans = [ 3, 1, 2] [ 4, 5, 6] [ 8, 9, 7]
To sort the elements of each row, use set the value of the
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 = 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
sort(X, 2, 'descend')
ans = [ 8, 6, 1] [ 7, 5, 3] [ 9, 4, 2]
X— Input that needs to be sorted
Input that needs to be sorted, specified as a symbolic vector or matrix.
dim— Dimension to operate along
Dimension to operate along, specified as a positive integer.
The default value is
the number of dimensions of
[Y,I] = sort(X,dim) returns
Y = X and
Y— Sorted output
Sorted output, returned as a symbolic vector or matrix.
sort for vectors or matrices
of numbers that are not symbolic objects invokes the MATLAB®
For complex input
elements by their magnitudes (complex moduli), computed with
If complex numbers have the same complex modulus,
their phase angles,
If you use
'ascend' instead of
sort returns elements in ascending order,
as it does by default.
sort uses the following rules:
It sorts symbolic numbers and floating-point numbers numerically.
It sorts symbolic variables alphabetically.
In all other cases, including symbolic expressions
sort uses internal sorting rules.