next up previous contents
Next: 6.2 Branching Up: 6. Real programming Previous: 6. Real programming   Contents

6.1 Loops

MATLAB has two distinct looping constructs: for loops and while loops. for loops are useful for repeating a process a certain number of times while a while loop is useful for repeating a process until a specified condition is met. As an example, let us suppose we wish to print out the reciprocals of all of the integers up to 10. Type this,
% My first loop
for i=1:10 % start at 1 and go to 10
    disp([i,1/i]) % print the integers and their reciprocals
end % the end of every for loop must be "closed" using the end statement
The 1:10 argument of the for loop tells MATLAB to start at 1 and loop until the loop variable i reaches 10. A for loop always has a loop variable. In this case, every time the loop is executed the value of i is incremented by 1. All of the commands between the for and the end statements (just disp in this case) are executed each pass through the loop. The disp command merely makes the output less cluttered (leaves out the ans = part of the output). The increment of the loop does not have to be 1 or even be increasing. Try this,
% Other increments besides 1
for i=1:2:10 % start at 1 and go to 10 by 2's
    disp([i,1/i]) % print the odd integers and their reciprocals
end % the end of every for loop must be "closed" using the end statement
disp('And now going backwards')
for j=10:-1:6 % start at 10 and go backwards to 6 by 1's
    disp([j,1/j]) % print the integers and their reciprocals
end % the end of every for loop must be "closed" using the end statement
In this example, the increment of the loop was also specified in the for statement. The general syntax for the for statement is: start:increment:end. If the increment value is omitted, it is understood to be 1. Before going on, demonstrate that you understand how to use for loops by printing out, in reverse order, all of the integers between 1 and 100 that are divisible by 3. Show your working program to the instructor. Loop and branch statements can also be nested. Try this,
% Nested loops
for i=1:4
    for j=1:3
        disp([i j i*j]) 
    end
end 
Note that it's the inner loop that increments the fastest (j changes every pass through the loop but i changes only once every time the j loop finishes). A final word of caution, never assign a value to the loop variable inside of the loop. Although doing so is somewhat innocuous in MATLAB, it can be really dangerous in languages such as Fortran95 or C++. One case where beginner programmers are tempted to do this is when they want to exit a for loop before the end value of the for loop has been reached. MATLAB (and other languages) have specific statement for doing this. In MATLAB the break command can be used for exiting a for loop before the declared ending value is actually reached. The other looping construct is the while loop. With this construct a series of statements can be executed until a specific condition is met. In the example, we'll add all the reciprocals of the positive integers until the current reciprocal is smaller than $10^{-3}$. When the current reciprocal is smaller than $10^{-3}$ then the condition of the while statement will no longer be true and the while loop will terminate.
format long g % Modify the output format for best display
i = 1; % start the counter at 1
total = 0; % initialize the sum
while(1/i >= 1e-3) % continue as long as 1/i is at least .001
    total = total + 1/i; % add the next reciprocal to the sum
    disp([i 1/i total]) % display the number of loops, 1/i, and the current sum
    i = i + 1; % add 1 to the counter
end
(Please notice that we use ``total'' as a variable to store the sum and not ``sum.'' sum is a standard MATLAB function. It's a really bad idea to use variable names that are already defined as MATLAB functions.) Here's an example that shows how round-off error in the computer leads to finite precision of arithmetic in the computer. The while loop is repeated until its condition is no longer true.
n_loops = 0; epsilon = 1;
while (1+epsilon) > 1
    epsilon = epsilon/2;
    n_loops = n_loops + 1;
end
n_loops
epsilon
In this example, the variable epsilon becomes smaller and smaller until adding it to 1 no longer has any effect, even though it is still larger than zero. After 53 passes through the loop, epsilon has become very small and adding it to 1 yields 1! This is not because epsilon is zero but because it is so small that the difference between 1 and $1+\epsilon$ is too small to be represented by the computer. We'll talk more about the implications of finite arithmetic later in the tutorial.
next up previous contents
Next: 6.2 Branching Up: 6. Real programming Previous: 6. Real programming   Contents
Gus Hart 2005-01-28