.. _loops: For Loops =========== Here we introduce our first programming *control construct*. Control constructs determine which, if any, code is executed, and how many times the code is executed. The ``for`` loop is considered a *counting loop* because the loop’s declaration explicitly states the number of times that the loop will execute. Code Blocks ------------- A *code block* is a set of commands grouped together to perform a task. A code block may be a single command, or it may be a large section of code. Different programming languages use different strategies to identify a code block. In MATLAB, a code block is all of the code between the initial line of the control construct (in this case, ``for``) and the keyword ``end``. For Loop Syntax ----------------- Here is the syntax of a ``for`` loop. :: for idx = sequence code block end Here, *sequence* is a series of values (usually numbers in the form of a row vector). Here is an example ``for`` loop. The variable ``k`` sequentially gets the next value of the sequence each time the code block runs. The variable ``k`` is 1 the first time through the loop. On the second iteration, ``k`` is 2. During the third and final execution of the loop, ``k`` is 3. :: for k = 1:3 disp(['Iteration: ',num2str(k)]) disp(2*k) end The output from this loop is: :: Iteration: 1 2 Iteration: 2 4 Iteration: 3 6 Colon Sequences ----------------- The colon operator, as used in the previous example, is frequently used to create a sequence of numbers. The simplest colon operator usage takes two arguments and counts with a step size of one between the two arguments. :: >> 1:5 ans = 1 2 3 4 5 >> 3:7 ans = 3 4 5 6 7 >> 1.5:4.5 ans = 1.500 2.500 3.500 4.500 With three arguments, the first and third arguments specify the range as before, while the second argument gives the step size between items of the sequence. :: >> 1:2:5 ans = 1 3 5 >> -12:4:12 ans = -12 -8 -4 0 4 8 12 >> 0:0.5:3 ans = 0 0.500 1.000 1.500 2.000 2.500 3.000 >> 3:-1:0 ans = 3 2 1 0 .. index:: code block .. index:: for loop .. index:: colon operator .. index:: sequence Application of For Loops in MATLAB ------------------------------------ A ``for`` loop is often used to iterate through a sequence of values or items in an array, which is a cornerstone of numerical computing. Although syntax differences exist, ``for`` loops are a significant component of every computer programming language. However, as we will see in :ref:`vectors`, and :ref:`vectorizing`, MATLAB does not always need a ``for`` loop to iterate through an array. Element-wise arithmetic and functions that operate on all of the values in a vector can be used instead of a ``for`` loop. In MATLAB, ``for`` loops are needed to execute algorithms with different parameters or data sets, but not usually to apply a calculation to a single data set. For example, one might use a ``for`` loop to plot a series of data curves in a chart. Whereas, the data for each curve on the chart might be generated using element-wise arithmetic and vector-aware functions. Fibonacci Sequence -------------------- The Fibonacci sequence of numbers is an exception to what was said earlier about not usually needing loops to generate data values in MATLAB because each value is derived from previously calculated values. This is the first example where we will use an array (vector) to save the results. We will discuss arrays more in :ref:`vectors`. We preallocate the array with the ``zeros`` function. The definition of the Fibonacci sequence is :math:`F_1 = 0`, :math:`F_2 = 1`, and :math:`F_i = F_{i-1} + F_{i-2}` for :math:`i \geq 3`. :: n = 50; % number of terms F = zeros(1,n); % F(1) = 0 -- already set F(2) = 1 for i = 3:n F(i) = F(i-1) + F(i-2); end .. topic:: Fibonacci sequence The Fibonacci sequence is interesting because it is a series of numbers that naturally occurs in nature. It is also a sequence that the computer science education world has latched onto because it can be implemented in various ways to teach programming concepts and to illustrate programming strategies. A simple recursive function runs very slowly because the program recalculates values many times. Using dynamic programming greatly improves the performance, and we will see in :ref:`differenceEq` that there is also a closed-form (not iterative) equation for calculating Fibonacci sequence values. First Plot ------------ .. index:: plot .. index:: hold on .. index:: hold off Plotting data will be discussed several times in the following chapters. Here we will use a ``for`` loop to plot a sequence of points. Start by entering the following in the Command Window: :: >> plot(1, 2, 'o') You should see a plot with a small circle at point :math:`(x = 1, y = 2)`. If you plot another point, the first plot is replaced by the new one. :: >> plot(2, 3, 'o') If we want multiple plots on the same figure, we want to use ``hold on`` to retain the same axis for all plots. When finished plotting, we issue the ``hold off`` command so that future plots start over. It is common to make the first ``plot`` to generate the graph and then use the ``hold on`` command before adding new plots, but we can also use a loop to make all of the plots after the ``hold on`` command. Copy the code from :ref:`forLoopPlot` into a MATLAB script. The appearance of the data points here are specified by the ``’r*’`` option, which calls for red asterisks with no connecting line. :: % File: firstPlot.m %% Plot k^2 for k = 0 to 5 hold on for k = 0:5 plot(k, k^2, 'r*'); end hold off %% title and axis labels title('Y = k^2') xlabel('k') ylabel('k^2') .. _forLoopPlot: .. figure:: forLoopPlot.png :figclass: center-caption :align: center :width: 40% :alt: A simple plot from a for Loop, each plot puts one marker on the plot. Simple plot from a ``for`` Loop **A peak ahead** A better way to code :ref:`forLoopPlot` is to pass a sequence of points to one plot command as follows. We will discuss finding the sequence of :math:`y` axis data points in :ref:`element-wise`. :: k = 0:5; plot(k, k.^2, 'r*'); A Multi-line Plot ------------------- The next example shows using a ``for`` loop to plot multiple lines. Note how MATLAB automatically uses a different color for each curve. Also note the legend displayed at the top of the plot. We discuss the details of plotting in the next chapter. Your plot should look like figure :numref:`fig-multiLinePlot`, except you should see colored plot curves. :: % File: multiline.m % Multiline plot with a for loop x = -1.5:0.1:1.5; style = ["-", "--", "-."]; hold on for k = 1:3 plot(x, x.^k, style(k), 'LineWidth', 2) end axis tight legend('y = x', 'y = x^2', 'y = x^3', 'Location', 'North') hold off .. _fig-multiLinePlot: .. figure:: multiPlot.png :figclass: center-caption :align: center :width: 40% :alt: Using a loop to plot multiple data curves on a plot. Using a loop to plot multiple data curves on a plot. .. index:: Fibonacci sequence