The simplest case is just preforming a task for a fixed known number of times. Say we want to display the numbers between 1 to n, we can write:
n = 5;
for k = 1:n
display(k)
end
The loop will execute the inner statement(s), everything between the for
and the end
, for n
times (5 in this example):
1
2
3
4
5
Here is another example:
n = 5;
for k = 1:n
disp(n-k+1:-1:1) % DISP uses more "clean" way to print on the screen
end
this time we use both the n
and k
in the loop, to create a "nested" display:
5 4 3 2 1
4 3 2 1
3 2 1
2 1
1