4.4: Selecting Elements

Matlab and Octave Programming for STEM Applications · LibreTexts

0%

Contents

    Text

    Size
    100%
    Theme
    Typeface
    Line length
    Spacing

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

    4.4: Selecting Elements

    You can select an element from a vector with parentheses:

    >> Y = [6 7 8 9]
    Y = 6    7     8     9
    
    >> Y(1)
    ans = 6
    
    >> Y(4)
    ans = 9

    This means that the first element of Y is 6 and the fourth element is 9. The number in parentheses is called the index because it indicates which element of the vector you want.

    The index can be a variable name or a mathematical expression:

    >> i = 1;
    >> Y(i)
    ans = 6
    >> Y(i+1)
    ans = 7

    We can use a loop to display the elements of Y:

    for i=1:4
         Y(i)
    end

    Each time through the loop we use a different value of i as an index into Y.

    In the previous example we had to know the number of elements in Y. We can make it more general by using the length function, which returns the number of elements in a vector:

    for i=1:length(Y)
         Y(i)
    end

    This version works for a vector of any length.


    This page titled 4.4: Selecting Elements was last modified on Wed, 13 Jul 2022 23:38:25 GMT and is shared under a CC BY-NC-SA 4.0 license and was authored, remixed, and/or curated by Allen B. Downey (Green Tea Press) via source content that was edited to the style and standards of the LibreTexts platform.