2.5. For Loops

Reading Assignment

Please read chapter 3 of Physical Modeling in MATLAB, by Allen B. Downey [DOWNEY11].

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.

2.5.1. Code Blocks

A sequential collection of commands are often grouped together as a set that together perform some task. This set of commands is called a code block. A code block may be a single command or it may be a large section of code. When we discuss programming constructs, we will consider the code that is between the keywords of the construct as a single code block unit.

Different programming languages use different strategies to identify a code block. In MATLAB, a code block is all of the code between the keywords of the construct.

2.5.2. 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). The sequence could also be called a row vector, but we’ll get to that definition later.

The variable idx sequentially gets the next value of the sequence each time the code block runs.

Here is an example for loop. The variable k is 1 the first time through the loop. On the second iteration, k is 2. During the third a 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

2.5.3. Colon Sequences

The colon operator, as used in the previous example, is frequently used to create a sequence of numbers. They are used in for loops and also for several other purposes in MATLAB.

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.5000    2.5000    3.5000    4.5000

With three arguments, the first and third argument 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.5000    1.0000    1.5000    2.0000    2.5000    3.0000
>> 3:-1:0
ans =
    3     2     1     0

2.5.4. 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 there are implementation syntax differences, for loops are a major component of every computer programming language. However, as will be explained when we discuss Vectors and Matrices in MATLAB and Functions Operating on Vectors, MATLAB does not always need a for loop to iterate through an array. We will see how 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 set of data. For example, one might use a for loop to plot a series of data curves in a chart. Whereas, data for each curve on the chart might be generated using element-wise arithmetic and vector aware functions.

2.5.5. Fibonacci Sequence

The Fibonacci sequence of number is an exception to what was said earlier about not usually needing loops to generate data values in MATLAB. This is 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 the Vectors and Matrices in MATLAB section. Notice that we preallocate the array with the zeros() function.

The definition of the Fibonacci sequence is F_1 = 0, F_2 =
1, and F_i = F_{i-1} + F_{i-2} for 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

Note

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 various ways to both teach programming concepts and to illustrate programming strategies. A simple recursive function runs very slow because the program recalculates values many times. Using dynamic programming greatly improves the performance, and as we will see in the linear algebra chapter, there is also a closed form (not iterative) equation for calculating Fibonacci sequence values.

2.5.6. First Plot

Plotting data will be discussed several times in this course. Here we will use a for loop to plot a sequence of points. We will explore plotting in more detail later, but here we will keep it simple.

Start by entering the following in the Command Window:

>> plot(1, 2, 'o')

You should see a plot with a small circle at point (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 of the 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 the plots after the hold on command.

Copy the following code 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.

%% Plot k^2 for k = 0 to 5
hold on
for k = 0:5
    plot(k, k^2, 'r*');
end
hold off
%% Add a title and axis labels
title('Y = k^2')
xlabel('k')
ylabel('k^2')

You should see a plot like Figure Fig. 2.2.

A plot showing six red asterisks at y = k squared for k values of 0, 1, 2, 3, 4, and 5.

Fig. 2.2 Simple plot from a for Loop

A peak ahead

A better way to code the above plot is as follows. We will discuss what is happening here in Vectors and Matrices in MATLAB.

k = 0:5;
plot(k, k.^2, 'r*');

2.5.7. A Multi-line Plot

Run the following code for an example of when a for loop is needed to plot multiple lines. You will see a simple plot with three curves. Note how MATLAB automatics 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.

%% Multiline plot with a for loop

x = -1.5:0.1:1.5;
hold on
for k = 1:3
    plot(x, x.^k)
end
legend('y = x', 'y = x^2', 'y = x^3', 'Location', 'North')
hold off

Note

Now, please complete the homework assignment Fourier For Loop.