Sort array elements in ascending or descending order
B = sort(A)
B = sort(A,dim)
B = sort(...,mode)
[B,IX] = sort(A,...)
If A is a ...
Sorts the elements of A.
Sorts each column of A.
Sorts A along the first non-singleton dimension, and returns an array of sorted vectors.
Cell array of strings
Sorts the strings in ascending ASCII dictionary order, and returns a vector cell array of strings. The sort is case-sensitive; uppercase letters appear in the output before lowercase. You cannot use the dim or mode options with a cell array.
Integer, floating-point, logical, character, and categorical arrays are permitted. Floating-point arrays can be complex. For elements of A with identical values, the order of these elements is preserved in the sorted list. When A is complex, the elements are sorted by magnitude, i.e., abs(A), and where magnitudes are equal, further sorted by phase angle, i.e., angle(A), on the interval [−π, π]. If A includes any NaN or undefined categorical array elements, sort places these at the high end.
Ascending order (default)
[B,IX] = sort(A,...) also returns an array of indices IX, where size(IX) == size(A). If A is a vector, B = A(IX). If A is an m-by-n matrix, then each column of IX is a permutation vector of the corresponding column of A, such that
for j = 1:n B(:,j) = A(IX(:,j),j); end
If A has repeated elements of equal value, the returned indices preserve the original ordering.
If A has complex entries r and s, sort orders them according to the following rule: r appears before s in sort(A) if either of the following hold:
abs(r) < abs(s)
abs(r) = abs(s) and angle(r)<angle(s)
where −π < angle(r) ≤ π
v = [1 -1 i -i]; angle(v) ans = 0 3.1416 1.5708 -1.5708 sort(v) ans = 0 - 1.0000i 1.0000 0 + 1.0000i -1.0000
Sort horizontal vector A:
A = [78 23 10 100 45 5 6]; sort(A) ans = 5 6 10 23 45 78 100
Sort matrix A in each dimension:
A = [ 3 7 5 0 4 2 ]; sort(A,1) ans = 0 4 2 3 7 5 sort(A,2) ans = 3 5 7 0 2 4
Sort it again, this time returning an array of indices for the result:
[B, IX] = sort(A, 2) B = 3 5 7 0 2 4 IX = 1 3 2 1 3 2
Sort each column of matrix A in descending order:
A = [ 3 7 5 6 8 3 0 4 2 ]; sort(A,1,'descend') ans = 6 8 5 3 7 3 0 4 2
This is equivalent to
sort(A,'descend') ans = 6 8 5 3 7 3 0 4 2