This note aims at explaining the concept of iterations and loop constructs in MATLAB.

## Loops in MATLAB

Many programming algorithms require iteration, that is, the repetitive execution of a block of program statements. Similar to other programming languages, MATLAB also has built-in tools for iterative tasks in codes.

## For-loop

The for-loop is among the most useful MATLAB constructs. The general syntax of for-loop is,

for variable = expression
statements
end


Usually, expression is a vector of the form istart:stepSize:iend where fix((iend-istart)/stepSize+1) gives the number of iterations requested by the user, assuming iend>istart. The statements are the set of programming tasks that have to be repeated. For example consider a script named runForLoop.m,

for index = istart:stepSize:iend
disp(index);
end
disp( [ 'number of iterations: ', num2str( fix((iend-istart)/stepSize+1) ) ] );

>> istart = -2;
>> iend = 10;
>> stepSize = 3;
>> runForLoop

    -2
1
4
7
10
number of iterations: 5


You can also iterate in reverse order,

>> istart = 10;
>> iend = -2;
>> stepSize = -3;
>> runForLoop

    10
7
4
1
-2
number of iterations: 5


### Breaking a for-loop immaturely

You can also use break inside a for-loop to get out of it, even before the for-loop finishes the full number of iterations. This is specially useful when you want to ensure if a condition has happened, and if so, then terminate the for-loop. For example,

for integer = 1:10
disp(integer)
if (integer==5)
break
end
end

 1
2
3
4
5


#### Exercise

suppose you want to find the largest prime number that is smaller than a given input value by the user. Write a function that does so, using for-loop, break, and MATLAB’s intrinsic function isprime().

function integer = getPrime(upper)
if (upper<1)
disp('input value cannot be less than 1. Goodbye!')
return
end
for integer = upper:-1:1
if isprime(integer)
break
end
end
end


### Continue statement within for-loops

To skip the rest of the instructions in a loop and begin the next iteration, you can use a continue statement. For example, the following code prints only integers that are primes,

for integer = 1:10
if ~isprime(integer)
continue
end
disp(['prime detected! ',num2str(integer)])
end

prime detected! 2
prime detected! 3
prime detected! 5
prime detected! 7


### Iterating over vectors, matrices, and cell using for-loops

Note that the index of for-loop must not necessarily be an integer. Basically you can use the for-loop index to iterate over anything that is iterable in MATLAB. For example, consider the following,

a = [1,0,2,3,7,-1];
for index = a
disp(class(index))
disp(index)
end

double
1
double
0
double
2
double
3
double
7
double
-1


However, see what happens if we defined a as a matrix,

a = [1, 2, 3; 4, 5, 6; 7, 8, 9];
for index = a
disp(class(index))
disp(index)
end

double
1
4
7
double
2
5
8
double
3
6
9


What is happening here? The answer is that, MATLAB is a column-wise programming language, just like Fortran, and unlike C, C++ and all of their descendants. MATLAB, by default, iterates over elements of row vectors. Therefore, when you use a matrix as the iterator in for-loops, MATLAB considers an entire column as the index of for-loop. The same is also true for other multidimensional arrays in MATLAB, for example cell arrays,

a = {1, 2, 3; 4, 5, 6; 7, 8, 9};
for index = a
disp(class(index))
disp(index)
end

cell
[1]
[4]
[7]
cell
[2]
[5]
[8]
cell
[3]
[6]
[9]


Therefore, if you want to iterate over elements of a multidimensional matrix or array, you have to first reshape them using MATLAB’s built-in reshape() function to convert them to vector format, then iterating over them. For example,

a = {1, 2, 3; 4, 5, 6; 7, 8, 9};
a = reshape(a,[1,9]);
for index = a
disp(class(index))
disp(index)
end

cell
[1]
cell
[4]
cell
[7]
cell
[2]
cell
[5]
cell
[8]
cell
[3]
cell
[6]
cell
[9]


### Some general advice on for-loop index

• Avoid using $i$ and $j$ as index variables in for-loops. Note that i and j have special meanings in MATLAB, as described in previous notes. They are used to define complex numbers. Using these variable names as indices in MATLAB for-loops, would overwrite the default meaning of these variables.

• Avoid assigning a value to the index variable within the loop statements. The for statement overrides any changes made to index within the loop.

## While-loop

There is another iteration construct in MATLAB, called while-loop which has the following general syntax,

while expression
statements
end


The statements within the while-loop are executed as long as expression is true. For example,

x = realmax();
while x>0
xmin = x
x = log(x)
end
xmin

xmin =
1.7977e+308
x =
709.7827
xmin =
709.7827
x =
6.5650
xmin =
6.5650
x =
1.8817
xmin =
1.8817
x =
0.6322
xmin =
0.6322
x =
-0.4585
xmin =
0.6322


Note that, break and continue can be used in while-loops in the same fashion as they are used in for-loops, described above. The condition is evaluated before the body is executed, so it is possible to get zero iterations. It’s often a good idea to limit the number of repetitions to avoid infinite loops (as could happen above if x is infinite). This can be done in a number of ways, but the most common is to use break. For example,

n = 0;
while abs(x) > 1
x = x/2;
n = n+1;
if n > 50, break, end
end


A break immediately jumps execution to the first statement after the loop. It’s good practice to include some diagnostic output or other indication that an abnormal loop exit has occurred once the code reach the break statement.

### Exercise

Write function getFac(n) using while-loop, that calculates the factorial of an input number n. For example,

>> getFac(4)

4! = 24


function getFac(n)
nOrg = n;
fac = n;
while n > 1
n = n-1;
fac = fac*n;
end
disp([num2str(nOrg),'! = ' num2str(fac)])
end


### Some general advice on while-loops

• If you inadvertently create an infinite loop (that is, a loop that never ends on its own), stop execution of the loop by pressing Ctrl+C.

• If the conditional expression evaluates to a matrix, MATLAB evaluates the statements only if all elements in the matrix are true (nonzero). To execute statements if any element is true, wrap the expression in the any() function.

• To exit the loop, use a break statement as discussed above. To skip the rest of the instructions in the loop and begin the next iteration, use a continue statement.

• When nesting a number of while statements, each while statement requires an end keyword.