2.4. 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 in the loop’s declaration, the number of time that the loop will execute is explicitly stated.

2.4.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 just all of the code between the keywords of the construct.

2.4.2. For-Loop Syntax

Here is the syntax of a for loop.

for idx = sequence
    code block
end

Here, sequence is a series, a row vector, 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.4.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 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.4.4. Application of for loops in MATLAB

The functionality of a for loop to iterate through a sequence of values or items in an array is a cornerstone of numerical computing. Although there are implementation syntax differences, for loops are a major components of every computer programming language.

However, as will be explained when we discuss Vectors and Functions of Vectors, MATLAB has the ability to internally apply for loop functionality to data such that the MATLAB programmer has much less need to write a for loop as is needed with other programming languages. In MATLAB, for loops are needed to execute algorithms with different parameters or data sets rather than to apply a calculation to a single set of data. For example, one might use a for loop to a plot series of data curves in a chart figure. Whereas, a for loop might not typically be needed to generate the data of each curve on the chart.

2.4.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 example is also the first time where we will use an array (vector) to save the results. We will discuss arrays more in the Vectors section. Notice that we preallocate the array (ones() function), which improves the efficiency of our program and also sets the first two values of the Fibonacci sequence.

The definition of the Fibonacci sequence is F_1 = 1, F_2 = 1, and F_i = F_{i-1} + F_{i-2} for i \geq 3.

n = 50;  % number of terms
F = ones(1,n);
% F(1) = 1  -- already set
% F(2) = 1
for i = 3:n
    F(i) = F(i-1) + F(i-2);
end

2.4.6. First Plot

Plotting of data with be discussed several times in this course. Here we will use a for loop to plot a sequence of points. Later, we plot line curves and surfaces in various formats. This introductory plot keeps 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 place a loop to make all the plots after the hold on command.

Copy the following code into a MATLAB script. The data points here are specified as 'r*', which means 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 figure like the following.

../_images/forLoopPlot.png

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.

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

2.4.7. A Multi-line Plot

Run the following code for a better application of a for loop to plot multiple lines.

%% 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.