MATLAB does not provide a function to sort a 2D matrix by row.

## Preparation

Create a matrix using the following code:

``A = [2, 8, 5, 3; 4, 4, 1, 6; 9, 2, 7, 5];``

## Procedure

MATLAB does not provide a function to sort successively the columns of a matrix according to one or more rows, but you can do so using the following procedure:

1. Transpose the matrix
2. Sort the rows of the matrix using `sortrows`
3. Transpose the matrix
The function `sortrows` only supports 2D inputs.

## Example

Suppose that you need to sort the columns of `A` in ascending order according to the third row.

``````% Transpose
B = A';``````
``````% Sort by the third column (ASC)
B = sortrows(B,3);``````
``````% Transpose
B = B';``````

## Function

The following function encapsulates the procedure described above. It is properly documented and available for download here.

``````function B = sortcols(A,rows)
B = A';
B = sortrows(B,rows);
B = B';
end``````

To use `sortcols`, pass a 2D matrix and a vector of row indices. The sort is in ascending order by default. To sort in descending order, prepend a minus sign to the row index.

The file ‘sortcols.m’ must be in the current directory or in the MATLAB search path.
``````% Sort by the first row (ASC)
resultExample1 = sortcols(A,1);``````
``````% Sort by the second row (DESC) and then by the third row (ASC)
resultExample2 = sortcols(A,[-2,3]);``````

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 other tutorials in this series.

## Source code

I hope you have learned how to sort a 2D matrix by row in MATLAB. The source code developed in this tutorial is available at this page.