Sort elements of symbolic vectors or matrices
X is an
matrix and you sort elements of each column (
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
X is a two-dimensional matrix, and you sort the elements
of each column, the array
I shows the row indices that the
Y had in the original matrix
X. If you sort the elements of each row,
shows the original column indices.
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
Y had in the original vector or matrix
sort with two output
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,
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
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 in descending
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
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
dim exceeds the number
of dimensions of
[Y,I] = sort(X,dim)
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
abs(X). If complex numbers have the same complex modulus,
sort compares 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 and functions,
sort uses internal sorting rules.