Create a matrix using the following code:
A = [7, 4, 10; 2, 1, 8; 15, 16, 11];
A = 7 4 10 2 1 8 15 16 11
B = sort(A,dim,mode) sorts the elements of
A along the \(dim\)-th dimension, and stores the result in
mode is ‘ascend’, the result is in ascending order. If it is ‘descend’, the result is in descending order.
dimis 1, the elements of each column are sorted
dimis 2, the elements of each row are sorted
mode is not specified, it defaults to ‘ascend’. If
dim is not specified, it defaults to the first dimension whose size is greater than 1.
% Elements of each column in ascending order resultExample1 = sort(A,1);
resultExample1 = 2 1 8 7 4 10 15 16 11
% Elements of each column in descending order resultExample2 = sort(A,1,'descend');
resultExample2 = 15 16 11 7 4 10 2 1 8
% Elements of each row in ascending order resultExample3 = sort(A,2);
resultExample3 = 4 7 10 1 2 8 11 15 16
% Elements of each row in descending order resultExample4 = sort(A,2,'descend');
resultExample4 = 10 7 4 8 2 1 16 15 11
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 2D matrix in MATLAB. The source code developed in this tutorial is available at this page.