3.4: Common Vector Operations

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.4: Common Vector Operations

    Once we create vectors, we often need to combine them, access or delete certain elements, or change values inside them.

    Concatenating Vectors

    Concatenation means joining arrays together. For row vectors, we can place two vectors next to each other inside square brackets.

    Example \(\PageIndex{1}\)

    Concatinating vectors.

    array3 = 1:5;
    array4 = 9:-2:1;
    catArray = [array3 array4]
    Solution

    The result is one longer row vector containing the values of array3 followed by the values of array4.

    catArray =
    
    1 2 3 4 5 9 7 5 3 1


    Accessing Elements by Index

    Each element in a vector has an index, which tells us its position. MATLAB indexing starts at 1. This is important: the first element is element 1, not element 0.

    Example \(\PageIndex{2}\)

    Accessing elements.

    array3 = 1:5;
    arr_1 = array3(5) % returns the 5th element
    arr_2 = array3([1 3 5]) % returns the 1st, 3rd, and 5th elements
    arr_3 = array3(1:3) % returns the 1st through 3rd elements
    Solution
    arr_1 =
    
         5
    
    
    arr_2 =
    
         1     3     5
    
    
    arr_3 =
    
         1     2     3
    
    Caution

    Common mistake: Students with experience in languages such as Python, C, or Java sometimes try to use index 0. MATLAB starts counting at 1.

    Changing an Element

    To change a value stored in a vector, refer to its index and assign a new value.

    Example \(\PageIndex{3}\)

    Changing an element.

    array3 = 1:5;
    array3(5) = 100
    Solution
    array3 =
    
         1     2     3     4   100
    

    Now the fifth element of array3 is no longer 5; it is 100.


    This page titled 3.4: Common Vector Operations 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.