Tutorial

How to Sort a 2D Matrix by Column in MATLAB

The function sortrows sorts the rows of a 2D matrix according to one or more columns.

Preparation

Create a matrix using the following code:

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

Syntax

B = sortrows(A,columns) sorts successively the rows of A according to the columns specified by the vector of indices columns, and stores the result in B.

The sort is in ascending order by default. To sort in descending order, prepend a minus sign to the column index. If columns is not specified, it defaults to 1.

sortrows only supports 2D inputs.
% Sort by the first column (ASC)
resultExample1 = sortrows(A);
% Sort by the third column (DESC)
resultExample2 = sortrows(A,-3);
% Sort by the second column (ASC) and then by the third column (DESC)
resultExample3 = sortrows(A,[2,-3]);

Note: If a column index is out of range, MATLAB generates an error.

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

Exercise

Create a matrix using the following code:

X = [1, 4, 5, 7; 1, 6, 3, 7; 9, 6, 8, 7];
  1. Sort X in ascending order by the fourth column, then in descending order by the second column, and then in ascending order by the third column
  2. Sort X in ascending order by the fourth column, then in descending order by the second column, and then in descending order by the third column

Note: Store the result of each clause in a new variable. Compare visually the result of both clauses.

Source code

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

Share

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