Repetitive tasks

Loops allow the user to repeat a calculation for a number of times. Recall that in a previous section, we showed a very contrived example for demonstrating the effect of rounding errors:

  format long
  x = 0.1
  y = 1
  z = y -(x+x+x+x+x+x+x+x+x+x)
Note the line where z is calculated. It is very tedious to have to write the sum of x 10 times in this way, let alone if we want to sum it even more times. It is also difficult to ensure that we've typed the right number of x's! Luckily, MATLAB allows us to replace a line like:
  z = y - (x+x+x+x+x+x+x+x+x+x)
by
  xsum = 0.0;
  for i = 1:10
     xsum = xsum + x
  end 
  z = y - xsum;
These two code segments produce identical results. The advantage of the second is that we don't have to manually count out how many X values we want to add together. It also means that if we decided to add 20 values, all we would have to do is change the 10 in the FOR statement to a 20.

In practice, you will encounter two forms of the program loop: a deterministic one in which the relevant code is executed a predetermined number of times (as in the example above) and one in which the number of times through the loop depends on the behaviour within the loop (for example, loops which terminate when a certain convergence criterion is met such as when using Newton's method for solving a system of nonlinear equations).

Deterministic loops - FOR

In a deterministic loop the limits of repetition are defined in advance. To do this we use a FOR loop. An example of such a loop was given above and another (slightly less trivial) example is given here:
  sum = 0
  for k = 1:20
     sum = sum + k^2
  end
disp('The sum of first 20 squared numbers is ')
disp(sum)
The FOR statement, in this form, expects an iteration variable or FOR loop index, which in the example is the variable k. The rest of the line tells the FOR loop what values this loop index must take. In this case, we have told it to start with the value of 1 and perform each iteration successively using values of 2, 3, and so on until 20.

In general, the starting statement of a deterministic loop has the form

  FOR variable = start: step : end
The code between the FOR and END statements will be repeated with values of index starting with start, incremented by step for each successive iteration until it exceeds the value of end. Note, if the step is given a negative value, the FOR loop will continue until the index is less than end. However, if the step is emitted it will automatically a step value of 1. For example:
  for i = 5:15   % do for between 5 and 15 with increments of 1
  for j = 1:2:19 % do for all odd numbers from 1 to 19
  for k = n:-1:1 % start at n and count down to 1 inclusive
Note that any of start, end, and step may be expressions as in:
    ...
  for i = 1:2:2*n+1
     ...
  end  
  ...
where the end of the loop depends on the value of n.

Also note that it is possible that no iterations through the FOR loop will happen. For example, if n above had a negative value, it would evaluate to something less than 0 and since the starting value is greater than 0 (with a positive step size), the terminating condition for the FOR loop is met before we even start. In this case, execution would proceed immediately to the code after the END.

The value of the loop variable index is incremented at the end of the loop iteration for use in the subsequent iteration. As a result, upon exit from the FOR loop, the value of the index variable will be some value greater than END (how much greater depends on the step...) It is useful to bear this in mind when subsequent use of the index variable is required. In practice, it is better to not assume that the index variable has any specific value after leaving the FOR loop and hence should not be used.

Non-Deterministic loops - WHILE

The second form of loop is when there are no specified limits for the loop parameters. The condition to end the loop calculation is only satisfied during the execution of the loop itself. To do this we use a a WHILE loop.
  t_start = 0.0 ; % starting time
  t_end = 1.0   ;  % end time
  delta_t = 0.1 ;  % time step
  t = t_start;
  i = 1 ;

  while  t < t_end
   % calculate something using the time t
       y =  2*t^3 - 5*t;
   % Record output in matrix
      tabulate(i,1) = t;
      tabulate(i,2) = y;
       i = i +1;
  % increment time using the time step value
      t = t + delta_t;
  end  % end while

  % Output results to screen
  disp('       t         y') 
  disp(tabulate) 
 
Although this example could have been done using a FOR loop , calculating the number of times we expect to go through the loop before hand, it is often easier and more readable to simply let the important variable (the time in this case) control the execution of the loop.

The WHILE loop is terminated when the appropriate condition is met (we reach the value of t_end).

Important: This form of WHILE loop, without an explicit statement of how many times to perform the loop itself, can be dangerous if not used carefully. One MUST always, in a case like this, use some counter that ensures that a WHILE loop will eventually terminate. The example above is safe as the time variable will eventually reach and exceed the value of t_end. In the following example, however, there is no such guarantee:

  x = 1.0
  while x > 0  % leave when value becomes negative
    ! estimate new value of x
    x = x^2 - 10*x + sin(x)
  end
  ...
Depending on what the right hand side of the assignment statement evaluates to, the condition for exiting the WHILE loop might never occur. In a case like this, one must always include a mechanism to ensure the WHILE loop is exited, as in the following, safer, alternative:
  max_counter = 50;
  counter = 1;
  x = 1.0;
  while x > 0     % leave when value becomes negative
    % estimate new value of x
    x = x^2 - 10*x + sin(x);

  % Check to see if we've exceeded maximum iterations allowed
    counter = counter + 1;
    if counter > max_counter 
      disp('Maximum iterations allowed has been exceeded!')
      break
    end  % if
  end    % while
  ...
This WHILE loop will now always terminate by the time 50 iterations are performed (it may, of course, terminate much sooner, depending on the value of x). Note how we've informed the user that something may have gone wrong. In practice, the error message would hopefully be a lot more informative!!

Nesting loops

Just as we've seen an IF statement inside a FOR loop, we can have FOR or WHILE loops inside other such loops. For example:
  y = 0;
  x = 0;
  for i=1:10
     y = y + i^2;
     for j= 1:i
        x = x + j;
     end 
  end
  x
  y 
Here we see an inner FOR loop inside another.

Click HERE for next section.