4.13: Sorting Arrays

Fundamentals of MATLAB Programming · LibreTexts

0%

Contents

    Text

    Size
    100%
    Theme
    Typeface
    Line length
    Spacing

    From LibreTexts, under CC BY-NC-SA, as the source states it; its equations are written in TeX, which the PDF shows typeset. This page at LibreTexts.

    4.13: Sorting Arrays

    The sort function arranges values in ascending order by default. For a row or column vector, this is straightforward. For a 2D array, MATLAB sorts each column independently.

    Example \(\PageIndex{1}\)

    Using sort

    rowEx = [76, 75, 40, 66, 18]; 
    
    sortedRowEx = sort(rowEx) % sorts the row vector
    
    
    colEx = [71; 4; 28; 5; 10]; % sort the column vector
    
    sortedColEx = sort(colEx)
    
    
    array2 = [29, 90, 14, 85;
              51, 96, 15, 26;
              70, 55, 14, 82];
    
    sortedArray2 = sort(array2) % sort the 2D array

    Solution

    sortedRowEx =
    
       18   40   66   75   76
    
    sortedColEx =
    
        4
        5
       10
       28
       71
    
    sortedArray2 =
    
       29   55   14   26
       51   90   14   82
       70   96   15   85

    To sort in descending order, use the second input argument "descend".

    sort(rowEx, 'descend')

    This page titled 4.13: Sorting Arrays was last modified on Tue, 30 Jun 2026 02:11:57 GMT and is shared under a CC BY-NC-SA license and was authored, remixed, and/or curated by Zara Noroozi.