3.5: Extending and Deleting Elements

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.

    3.5: Extending and Deleting Elements

    Extending a Vector

    MATLAB can extend a vector if you assign a value to a new index beyond the current length of the vector.

    Example \(\PageIndex{1}\)
    array3 = 1:5;
    array3(6) = 200
    Solution
    array3 =
    
        1 2 3 4 5 200

    This adds a sixth element to the vector.



    If you skip positions, MATLAB fills the missing locations with zeros.

    Example \(\PageIndex{2}\)

    Skipping positions.

    emptyVec(1) = 3
    emptyVec(4) = 11
    Solution
    emptyVec =
    
         3     0     0    11

    The result is a vector where the second and third elements are filled with 0. This can be useful, but it can also accidentally create large arrays if the wrong index is used.



    Deleting Elements

    To delete elements from a vector, assign empty square brackets to those positions.

    Example \(\PageIndex{3}\)

    Deleting elements

    newVec = 1:7
    newVec(3) = []    % deletes the third element
    newVec(2:4) = []  % deletes elements 2 through 4 of the remaining vector
    
    Solution
    newVec =
    
         1     2     3     4     5     6     7
    
    
    newVec =
    
         1     2     4     5     6     7
    
    
    newVec =
    
         1     6     7

    After each deletion, the vector becomes shorter and the remaining elements shift to fill the empty space.

    Using the end Keyword

    If you want the last element of a vector, you do not have to count how many elements it contains. Use the keyword end.

    Example \(\PageIndex{4}\)

    Using the end keyword

    newVec = 1:7;
    endNum = newVec(end)
    oneToEndNum = newVec(end-1)
    Solution
    endNum =
    
         7
    
    
    oneToEndNum =
    
         6
    

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