Iteration
Often when we are writing code, we want to the program to repeat (or iterate) the same or a similar action many times. For example, suppose we wish to sum the odd integers from 1 to 9. We could do this in Matlab using the following code:
sum = 0; sum = sum + 1; sum = sum + 3; sum = sum + 5; sum = sum + 7; sum = sum + 9
Of course we could have done this in one line of Matlab code:
sum = 1 + 3 + 5 + 7 + 9
Suppose we want to sum the odd integers from 1 to 1,000,001. Neither of our previous strategies for doing this would be very practical. And the situation can even be "worse": suppose we want to sum the odd integers from 1 to N where N is some number that will be given to us later. We can't even write out all the code to do this since we don't know how many numbers we will be adding!
The way to perform some sequence of statements for a specific list of values, or for a certain number of times,
is to use an iterative programming structure known as a for
loop.
The next lesson covers how to repeat a sequence of statements an unknown number of times.
If we know how many times a sequence is going to execute,
it is easiest to write it as a for
loop.
In Matlab, the for
loop has the structure :
for k = first : increment : last statements % body of for loop end
You will learn about the details of the for
loop structure in the next
lesson.