The function sort sorts matrices.

## Preparation

Create a matrix using the following code:

A = [7, 4, 10; 2, 1, 8; 15, 16, 11];

## Syntax

B = sort(A,dim,mode) sorts the elements of A along the $$dim$$-th dimension, and stores the result in B. If mode is ‘ascend’, the result is in ascending order. If it is ‘descend’, the result is in descending order.

• If dim is 1, the elements of each column are sorted
• If dim is 2, the elements of each row are sorted

If 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);
% Elements of each column in descending order
resultExample2 = sort(A,1,'descend');
% Elements of each row in ascending order
resultExample3 = sort(A,2);
% Elements of each row in descending order
resultExample4 = sort(A,2,'descend');

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.

1. This book was the winner of a Textbook Excellence Award. Chapter 14 covers matrix sorting, curve fitting, complex numbers, integration, differentiation, and other topics.

2. 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.

doc sort;

## Source code

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.