4.7: Flattening and Deleting Parts of a Matrix

Fundamentals of MATLAB Programming · LibreTexts

0%

Contents

    Text

    Size
    100%
    Theme
    Typeface
    Line length
    Spacing

    Read aloud

    How

    Speed: 1×
    Light up
    Highlight

    Symbols: Mulberry Symbols, © 2018–2026 Steve Lee, CC BY-SA 4.0 (licence, the set), the site's own copies.

    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.7: Flattening and Deleting Parts of a Matrix

    Flattening a Matrix

    Sometimes we want to treat all elements of a matrix as one long column. In MATLAB, we can flatten a matrix using a colon inside parentheses.

    Example \(\PageIndex{1}\)
    myArray = [1, 2; 3, 7];
    myArray(:)
    Solution
    ans =
    
        1
        3
        2
        7

    MATLAB reads the matrix column by column when it flattens the matrix. This is important because many MATLAB functions use column-major order internally.

    Note

    Why does MATLAB flatten column-wise?

    MATLAB stores arrays in memory by columns. That means it works down the first column, then down the second column, and so on.

    Deleting Rows and Columns

    You can delete an entire row or column by assigning an empty array, [], to that row or column.

    Example \(\PageIndex{2}\)

    Deleting a row and column.

    sampleMatrix = [1, 2, 3; 5, 7, 11; 13, 17, 19];
    
    sampleMatrix(2,:) = [] % delete second row
    sampleMatrix(:,2) = [] % delete second column from the remaining matrix
    Solution
    sampleMatrix =
    
        1 2 3
        13 17 19
    
    
    sampleMatrix =
    
        1 3
        13 19

    However, you cannot delete a single element from the middle of a 2D array, because that would leave a hole in the rectangular shape of the matrix.

    sampleMatrix(2,2) = []   % this will not work

    This page titled 4.7: Flattening and Deleting Parts of a Matrix 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.