Loops and Control

Sometimes, you do need to use some kind of loop to do what you need, rather than just operating on an entire matrix or vector at once.

While Loops

The syntax for a while loop is
while (some logical expression)
	do something;
	do something else;
To keep this from going on forever, you should probably be changing some variable in the logical expression within the body of the loop so that it eventually is not true.


The syntax for a for loop is:
          FOR X = 1:N,
                     A(X) = 1/(2+X-1);
You should try to avoid using i and j as counters, since you will wind up redefining i (which is intially defined as the imaginary i.)


The syntax for an if statement is

if (logical expression)
	matlab command
elseif (other logical expression)
	another matlab command
	a matlab command
(You don't need an elseif or an else, but you do need an end.)


The break command breaks you out of the innermost for or while loop you are in.

In the process of a loop, if you define an element of an vector that doesn't exist yet (the vector is smaller than the element you're trying to assign), matlab will increase the size of the vector or matrix to allow for the new element to go where you've specified. However, if you know that you're going to be assigning elements until the matrix grows to be some specific size, it's better to "preallocate" the matrix by defining it to be all zeros initially.

 matrix = zeros(rows,columns);
will do that.

Examples of some loops are in the file fors.m in the 2.670 Examples directory. (

 type fors.m