Aqua Phoenix
     >>  Lectures >>  Matlab 3  
 

Navigator
   
 
       
   

3.1 Loops

When performing an operation on a vector, such as squaring its elements, what really happens is that Matlab walks through the arrays, element-by-element, and squares the scalar in each array position. This process is performed in a loop.

The notable elements of a loop are

  1. some range that has a beginning and an end, typically something like a through b, e.g. 1 through 10.
  2. a body of statements which get executed for each element in the range.

For example, walking from 42nd St. to 116th St. can be described in the following loop: For each street starting at 42nd St. and ending at 116th St.: Walk from current street one block north to next street.

In the example of squaring the elements in vector A, we would have the following loop: For each element in A starting at element 1 up to the last element, square the element and go to the next position. The inherent operation of squaring is the same for each element in the array, only that the number that is squared changes.

Whenever some operation (the body) is to be performed a certain number of times, a loop comes in handy.

For example, squaring the numbers 1 through 10 in a loop is performed as:

for i=1:10
  i^2
end
The first line denotes the range over which this loop is executed, the second line is the body in which the actual computation takes place, and the third line denotes the end of the loop. The variable i in this loop acts as a loop variable. For each step (also called iteration) of the loop, i assumes the value of the current step in the range. Since the loop begins at 1, i assumes value 1 until we reach the end of the loop. Next in the range is 2, hence i=2 for the second iteration. Once i has assumed the last number in the range, the loop terminates, which is itself not only a desirable but also necessary attribute of a loop.

Figure 3.2 graphically shows every step that is performed in the loop.

Figure 3.1
Click image to enlarge, or click here to open
Figure 3.2
More often loop variables are used to index into arrays and matrices, rather than involving the loop variable directly in a computation.

a=[3,40,1,8,0]
b=[-7,5,-.4,16,1]
c=[]

for i=1:5
  c(i) = a(i) + b(i);
end
Figure 3.4 graphically shows the execution of this loop.

Figure 3.3
Click image to enlarge, or click here to open
Figure 3.4
When indexing into an array we know for a fact that the array starts at position 1, but in general we do not know how long the array is. In the previous example, a and b were defined to be of length 5, i.e. each array contains 5 elements, and hence the loop ranged from 1 to 5 (1:5). Should the arrays grow or shrink, their size is no longer 5, and in order to iterate over the array's elements, the range would need to be modified to 1:n where n is the new length. Instead of physically changing the code for the loop every time the array assumes a new length, we do not use a constant number for n in 1:n (e.g. 5 in 1:5), but instead a function that instantaneously returns the actual length of the array: length(a) where a is the array. The previous code can be rewritten as follows to make it more general:

for i=1:length(a)
  c(i) = a(i) + b(i);
end

Figure 3.5
Click image to enlarge, or click here to open
While a vector has one dimension over which a loop variable can iterate, a matrix has two dimensions: rows and columns. To iterate over an entire matrix, we ths need to iterate over every row and for each row over every column. This is called a nested loop, i.e. a loop within a loop:

m=[1,2,3,4;5,6,7,8;9,10,11,12]

for i=1:3
  for j=1:4
    m(i,j) = m(i,j) * 2;
  end
end

Figure 3.6
Click image to enlarge, or click here to open
Figure 3.7 graphically shows the execution of this nested loop code.

While loop variable i iterates over rows, loop variable j iterates over every column within the current row. As there are 3 rows in the matrix, the inner loop (the nested loop) is executed 3 times. Since the nested loop itself iterates 4 times, the body of the loop is executed 3*4 times, which corresponds to the number of elements in the matrix.

Figure 3.7
Again, the loop above can be generalized so that the loop statements are not confined to only 3*4 matrices. Since a matrix has more than one dimension, the one dimensional function length() cannot be used. Instead, we use function size() which returns the length for each dimension of the matrix:

m=[1,2,3,4;5,6,7,8;9,10,11,12]

l=size(m)

for i=1:l(1)
  for j=1:l(2)
    m(i,j) = m(i,j) * 2;
  end
end

Figure 3.8
Click image to enlarge, or click here to open
For higher order matrices, the number of loops required to visit each element in the matrix corresponds to the dimension. E.g. a 3 dimensional matrix such as the one for a full-color image might look as follows:

for i=1:height
  for j=1:width
    for k=1:3
      ... do something ...
    end
  end
end
The outer loop iterates over rows, the middle loop over columns, and the innermost loop over the 3 colors (Red, Green, Blue). Note that the body of this loop is accessed as many times as width*height*3.

There exist two kinds of loops: " for" and "while" loops. The "for" loop (discussed above) tends to be used in a scenario in which the range over which the loop iterates is strictly defined. In the above examples, the ranges were defined as 1:5 or 1:length(a), etc. The "while" loop tends to be used in scenarios in which the range is not well defined, for example in user input.

If we were to write a program that takes as input the names of students in a class, we might not know how many students there are. The corresponding while loop would look somewhat like this: While there are more unknown students: take the next unknown student's name.While loops can also be used if a range is not constantly increasing or decreasing. In the previous examples, all loop variables increased by a value of 1 for each loop. Should the array indices which we intend to visit not be 1,2,3,4,5 but instead 1,5,2,4,3,1,2,4,5,2,1,5 according to some formula within the loop for example, then a while loop is best used.

We can rewrite the above loop for adding two vectors as follows:

a=[3,40,1,8,0]
b=[-7,5,-.4,16,1]
c=[]

i=1;
while (i <= 5)
  c(i) = a(i) + b(i);
  i=i+1;
end
This has the same effect, only that the loop looks somewhat different.

There is no right or wrong in using one type of loop over another, but merely style and simplicity. Choose what you think makes most sense or what is simplest for the problem at hand.

Figure 3.9
Click image to enlarge, or click here to open