Matlab and Octave Programming for STEM Applications · LibreTexts
0%
Contents
Text
Size
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
Opening the book…
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: