Lab 4
Lab 4
Lab 4
In addition to conditional statements, the second fundamental type of programming construct that
we will consider in this lab is the iteration statement. Iteration statements are intended for use in
situations in which one or more operations need to be repeatedly performed several times. In
computer programming, iteration statements are often known as loop statements. In medical
analogy, it could involve performing blood tests and modifying the drug dosage repeatedly until
certain conditions in the blood test result are met (i.e. the patient has responded satisfactorily).
There are two types of iteration statement provided in MATLAB. In this section, we consider the for
loop. The control flow of a MATLAB for loop is shown in Fig. 4.1. Iteratively, the same statement, or
set of statements, is executed several times. In Fig. 4.1 the statement is continually executed until a
certain condition becomes false. A loop variable will be updated in each iteration to take on a different
value from an array, which has been initialized at the beginning of the for loop. When the statement
has been executed once for each element of the array, the condition becomes false.
4.2.1 Example
for loops can be useful when we want to execute some statements a fixed number of times. Consider
the following example first, then we will return to the flow chart in Fig. 4.1.
n = input('Enter number:');
f=1
if (n >= 0)
for i = 2:n
f = f*i;
end
else
end
This code reads in a number from the user and computes its factorial. (Note that MATLAB has a built-
in function to compute factorials: it’s called factorial.) The code first checks to see if the number is
greater than or equal to zero. If not, program execution jumps to after the else statement and an error
message is displayed. If it is greater than or equal to zero, the program executes the statement f = f i
once for each value in the array 2:n. During each pass through the loop (an iteration), the variable I
takes on the value of the current element of the array. So, for the first iteration i=2, for the second
iteration i=3, and so on, until i takes on the value of n.
Note how the assignment statement inside the for loop (f = f i) has the variable f appearing on both
sides. This might seem a little strange and it is important to understand here that the part of the
statement on the right-hand side of the assignment operator (=) is evaluated first using the current
value of f. The result of multiplying f by the current value of the loop variable i is found and it is then
assigned to f. In other words, the value of f is updated. After this the for loop proceeds to the next
iteration.
After the loop has finished all of its iterations (i.e. i has taken on all values of the array 2:n and f = f i
has been executed for each one), it exits and program execution continues after the end statement.
Since f was initialized to 1, the effect of iterating through the loop is to multiply 1 by every integer
between 2 and n. In other words, it computes the factorial of n.
Try typing in this code, saving it as a script m-file and running it. Read through it carefully to make sure
you understand how it works.
Now let’s return to the flow chart in Fig. 2.3. First, the initialize array and loop variable box
corresponds, in our MATLAB example, to setting up the array 2: n and initializing i to its first element.
The condition is to test if we have come to the end of the array. When we reach the end, the condition
becomes false, and the loop will exit. The statement corresponds to f = f i.
The update loop variable box will modify i so that it takes on the value of the next element in the array.
Generally, for loops are appropriate when it is known, before starting, exactly how many times the
loop should be executed. For instance, in Example 2.5 the value of n was entered by the user so the
number of loop iterations could be determined from this value. If it is not possible to know how many
times the loop should be executed, an alternative iteration construct is necessary, as will be described
below.
4.3 Iteration: WHILE Loops
The second type of iteration statement available in MATLAB is the while loop. The control flow of a
while loop is shown in Fig. 2.4. First, a condition is tested. If this condition evaluates to false, then
control immediately passes beyond the while statement. If it evaluates to true, then a statement (or
sequence of statements) is executed, and the condition is retested. This iteration continues until the
condition evaluates to false. Therefore, a while loop will execute continually until some condition is
no longer met. This type of behavior can be useful when continued loop execution depends upon
some computation or input that cannot be known before the loop starts.
4.3.1 Example
guess = -1;
while (guess ~= i)
if (guess == i)
disp('Correct!');
else
end
end
This program first generates a random integer between 0 and 9. The MATLAB randi statement, used
in this way, generates a random integer from a uniform distribution between 1 and its argument (in
this case, 10), so by subtracting 1 from this we can get a random integer between 0 and 9. The
following while loop will iterate whilst the condition guess ~= i is true. In other words, the loop will
execute so long as guess is not equal to the random integer i. Since guess is initialized to -1 before the
loop starts, the loop will always execute at least once. Inside the loop, a number is read from the user,
and an if statement is used to display an appropriate message depending upon whether the guessed
number is correct. The program will continue asking for guesses until the correct answer is entered.
Generally, while loops are useful when it is not known in advance how many times the loop should be
executed. Both for loops and while loops can be very useful, but in different types of situations. In
time you will learn to recognize when to use each of these types of iteration programming construct.
Any of the control structure statements we have covered can be nested. This simply means putting
one statement inside another one. We have already seen nested statements in some of the examples
and activities.
4.4.1 Example
As another example, examine the following piece of code and see if you can work out what it does.
while (n >= 0)
f = 1;
for i = 2:n
f = f*i;
end
disp(f);
end
Here, we have a for loop nested inside a while loop. The while loop reads in a sequence of numbers
from the user, terminated by a negative number. For each positive number entered, the for loop
computes its factorial, which is then displayed.
4.5 Tasks
4.5.1 Write a MATLAB script m-file that uses a for loop to compute the value of the
expression
Code
s=0;
b=0;
for a = 1:5
b = (a)^3+(a)^2+(a);
s = s+b;
disp(b)
end
disp(s);
Output
Figure 4.3
4.5.2 In a phase I clinical trial for a new drug one of the main goals is to determine the
recommended dose of the drug for phase II of the trial. Typically, the drug is tested on a small
cohort of patients with a low dose, and efficacy and toxicity are estimated. Then, the dose is
escalated (i.e. increased) and efficacy/toxicity are estimated on a new cohort. This process is
continued until toxicity becomes too high. The dose/toxicity results inform the choice of drug
dose for phase II of the trial. The increasing dose levels used in a phase I trial are known as the
dose escalation pattern. A common way of calculating the dose escalation pattern is to increase
the dose by 67% after the first cohort, by 50% after the second, by 40% after the third and by
33% after each subsequent cohort.
Code
b=0;
a=0.2;
for i = [0,.67,.50,.40,.33,.33,.33,.33,.33,.33]
b = a*i;
a = a+b;
disp(a)
end
Output
Figure 4.4
4.5.3 Write a MATLAB script m-file that continually displays random real numbers between 0
and 1, each time asking the user if they want to continue. If a ‘y’ is entered the program should
display another random number, if not it should terminate. Use a while loop in your
implementation.
Code
while(s=='y')
r = rand;
disp(r);
end
Output
Figure 4.5