The function sort sorts matrices.

## Preparation

Create a 3D matrix using the following code:

seed = [7, 2, 15, 4, 1, 16, 10, 8, 11];
items = [seed, seed - 5, seed + 5];
A = reshape(items,3,3,3);

## 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 dim is $$j$$, the elements are sorted along the $$j$$-th dimension

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.

Multidimensional matrix: Matrix with more than two dimensions.
% Elements of each column in ascending order
resultExample1 = sort(A,1);
% Elements of each row in descending order
resultExample2 = sort(A,2,'descend');
% Sort along the third dimension in descending order
X = sort(A,3,'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 2017 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 multidimensional matrix in MATLAB. The source code developed in this tutorial is available at this page.