Create a vector using the following code:
A = [7, 1, 5, 3, 6, 2, 4];
A = 7 1 5 3 6 2 4
B = sort(A,mode) sorts the elements of the vector
A and stores the result in
mode is ‘ascend’, the result is in ascending order. If it is ‘descend’, the result is in descending order.
modeis not specified, it defaults to ‘ascend’.
% Elements of A in ascending order resultExample1 = sort(A);
resultExample1 = 1 2 3 4 5 6 7
% Elements of A in descending order resultExample2 = sort(A,'descend');
resultExample2 = 7 6 5 4 3 2 1
Note: MATLAB treats
mode as a case-insensitive string, so ‘ascend’, ‘Ascend’ and ‘ASCEND’ are the same string.
I recommend the following books to learn more on matrix sorting in MATLAB.
This book was the winner of a Textbook Excellence Award. Chapter 14 covers matrix sorting, curve fitting, complex numbers, integration, differentiation, and other topics.
MATLAB for Engineers (5th Edition)
This excellent book is especially oriented to engineers and scientists who want to learn MATLAB programming. The third chapter covers matrix sorting and describes several data analysis functions, among other topics.
I also recommend the following page in the MATLAB help documentation, and the other tutorials in this series.
- How to Sort a Vector in MATLAB
- How to Sort a 2D Matrix in MATLAB
- How to Sort a Multidimensional Matrix in MATLAB
- How to Sort a 2D Matrix by Column in MATLAB
- How to Sort a 2D Matrix by Row in MATLAB
- How to Get the Elements of a Matrix in Ascending Order in MATLAB
- How to Get the Elements of a Matrix in Descending Order in MATLAB
I hope you have learned how to sort a vector in MATLAB. The source code developed in this tutorial is available at this page.