How to Sort a 2D Matrix by Row in MATLAB

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


Create a matrix using the following code:

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


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.


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';


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';

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]);

Further reading

I recommend the following books to learn more on matrix sorting in MATLAB.

  1. MATLAB: A Practical Introduction to Programming and Problem Solving (4th Edition)

    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.


Your friends may need this knowledge to complete a task. Share this tutorial.