illustration of for loop:
illustration, to print a column of numbers from 1 to 5:
for i = 1:5
fprintf('%d\n',i)
end
This loop can be entered in the Command Window, though like if and switch statements; loops will make more sense in the scripts and functions. In the Command Window, the outcome would appear after the for loop:
>> for i = 1:5
fprintf('%d\n',i)
end
1
2
3
4
5
What the for statement accomplished was to print the value of i and then the newline character for each value of i, from 1 through 5 in steps of 1. The first thing which happens is that i is initialized to have the value 1. Then, the action of loop is executed, that is the fprintf statement which prints the value of i (1), and then the newline character to move the cursor down. Then, i is incremented having the value of 2. Later, the action of the loop is executed, that prints 2 and the newline. Then, i is incremented to 3 and which is printed, then i is incremented to 4 and which is printed, and then finally i is incremented to 5 and which is printed. The final value of i is 5; this value can be used once the loop has completed.