Skip to main content
Engineering LibreTexts

4.4: Selecting Elements

  • Page ID
    85971
  • \( \newcommand{\vecs}[1]{\overset { \scriptstyle \rightharpoonup} {\mathbf{#1}} } \) \( \newcommand{\vecd}[1]{\overset{-\!-\!\rightharpoonup}{\vphantom{a}\smash {#1}}} \)\(\newcommand{\id}{\mathrm{id}}\) \( \newcommand{\Span}{\mathrm{span}}\) \( \newcommand{\kernel}{\mathrm{null}\,}\) \( \newcommand{\range}{\mathrm{range}\,}\) \( \newcommand{\RealPart}{\mathrm{Re}}\) \( \newcommand{\ImaginaryPart}{\mathrm{Im}}\) \( \newcommand{\Argument}{\mathrm{Arg}}\) \( \newcommand{\norm}[1]{\| #1 \|}\) \( \newcommand{\inner}[2]{\langle #1, #2 \rangle}\) \( \newcommand{\Span}{\mathrm{span}}\) \(\newcommand{\id}{\mathrm{id}}\) \( \newcommand{\Span}{\mathrm{span}}\) \( \newcommand{\kernel}{\mathrm{null}\,}\) \( \newcommand{\range}{\mathrm{range}\,}\) \( \newcommand{\RealPart}{\mathrm{Re}}\) \( \newcommand{\ImaginaryPart}{\mathrm{Im}}\) \( \newcommand{\Argument}{\mathrm{Arg}}\) \( \newcommand{\norm}[1]{\| #1 \|}\) \( \newcommand{\inner}[2]{\langle #1, #2 \rangle}\) \( \newcommand{\Span}{\mathrm{span}}\)\(\newcommand{\AA}{\unicode[.8,0]{x212B}}\)

    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 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; a detailed edit history is available upon request.