[Syntax description]
- B = sort(A); Along the direction of the different dimensions of the input parameter A, rearrange the elements in A from small to large. A can be a string, real, or complex cell array. If A is a complex number, it will be arranged in descending order of element amplitude. If there are complex elements with the same amplitude, they will be arranged in order of magnitude [-π,π] from largest to smallest. If A is a string, it is sorted in ASCII dictionary order. For vector A, sort(A) sorts the elements of A in ascending order; for matrix A, sort(A) sorts each column of A in ascending order.
- Y = sort(X,DIM,MODE); There are two optional parameters. DIM represents the dimension of the selection sort: 1 represents the column dimension, and 2 represents the row dimension. MODE indicates the direction of the selection sort:'ascend' means ascending order, and'descend' means descending order.
- [The Y, the I ] = Sort (X-, the DIM, the MODE); Returns an index matrix the I . If A is a vector, then Y = X(I). If A is an m×n matrix (DIM=1;), then each column in I is a permutation vector corresponding to the element of the column vector in A, and for j = 1:n, Y(:,j) = X(I(:,j),j); end.
[Example description]
- Example 1: Sort matrix a in ascending column dimension, and consider the role of index matrix. (The index matrix reveals the position of the elements in the original vector after rearrangement)
a=magic(3)
a =
8 1 6
3 5 7
4 9 2
[y,i]=sort(a)
y =
3 1 2
4 5 6
8 9 7
i =
2 1 3
3 2 1
1 3 2
for j = 1:3, b(:,j) = a(i(:,j),j); end
b
b =
3 1 2
4 5 6
8 9 7
- Example 2: Carry out eigenvalue decomposition on matrix A, arrange its eigenvalues in ascending order, and adjust the order of eigendiagonal matrix and eigenvector accordingly. (The following example can better illustrate the role of the index matrix)
A=magic(3)
A =
8 1 6
3 5 7
4 9 2
[V, D] = eig (A)
V =
-0.5774 -0.8131 -0.3416
-0.5774 0.4714 -0.4714
-0.5774 0.3416 0.8131
D =
15.0000 0 0
0 4.8990 0
0 0 -4.8990
[d,i]=sort(diag(D))
d =
-4.8990
4.8990
15.0000
i =
3
2
1
D=D(i,i)
D =
-4.8990 0 0
0 4.8990 0
0 0 15.0000
V=V(:,i) The column vector of %V is adjusted according to the adjustment order of D
V =
-0.3416 -0.8131 -0.5774
-0.4714 0.4714 -0.5774
0.8131 0.3416 -0.5774