Section 7.7 The for
loop
The MATLAB
for
loop repeats a given set of commands a specified number of times. MATLAB offers a few more options for the loop counter as compared to C. Take a look at these examples:The
for-end
loop syntax:for k = f:s:t % loop over all values of k from f to t in steps of s
commands
...
end
for k = f:t % default step is 1
commands
...
end
for k = [7 9 -1 3 3 5] % can specify array of values:
commands % loop repeats once for each value of the given vector
...
end
As in C, you loops can be nested. Here is an example:
Recall the program we worked on in C to print a list of factorials:
#include <stdio.h>
int main(void) {
int N, i, fact;
for (N=1; N<=10; N++) {
fact = 1;
for (i=1; i<=N; i++) {
fact = fact*i;
}
printf("%d! = %d\n", N, fact);
}
return 0;
}
This program computes and prints a list of the factorials from 1 to 10. We can translate this code into MATLAB:
for N = 1:10
fact = 1;
for i = 1:N
fact = fact*i;
end
fprintf('%d! = %d\n', N, fact)
end
But this is MATLAB! Of course we don’t really need to calculate our own factorial since there is a built-in function for that:
for N = 1:10
fprintf('%d! = %d\n', N, factorial(N))
end
And while we are at it, because MATLAB is vectorized we don’t even need the loop:
N = 1:10;
fprintf('%d! = %d\n', [N; factorial(N)])