How to Get the Elements of a Matrix in Descending Order in MATLAB

Use the colon operator and the sort function to get the elements of a matrix in descending order.


Create two matrices using the following code:

A = [9, 4, 7; 1, 11, 3];
B = [4, 15, 6, 8, 10, 1, 2, 9, 5, 7, 14, 3];
B = reshape(B,2,3,2);


Apply the following procedure to get the elements of a matrix in descending order:

  1. Get the matrix as a vector
  2. Sort the vector in descending order
This procedure works for matrices of any size.
% Elements of A in descending order
resultExample1 = sort(A(:),'descend');
% Elements of B in descending order
resultExample2 = sort(B(:),'descend');

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

Source code

I hope you have learned how to get the elements of a matrix in descending order 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.