Tutorial

How to Sort a Vector in MATLAB

The function sort sorts vectors and matrices.

Preparation

Create a vector using the following code:

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

Syntax

B = sort(A,mode) sorts the elements of the vector A 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 mode is not specified, it defaults to ‘ascend’.
% Elements of A in ascending order
resultExample1 = sort(A);
% Elements of A in descending order
resultExample2 = sort(A,'descend');

Note: MATLAB treats mode as a case-insensitive string, so ‘ascend’, ‘Ascend’ and ‘ASCEND’ are the same string.

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

Source code

I hope you have learned how to sort a vector 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.