3.4: for Loops
- Page ID
Let’s return to the bike-share example. In the previous chapter, we wrote a bikeupdate.m script to simulate a day in the life of a bike-share system. To simulate an entire month, we’d have to run the script 30 times. We could enter the same command 30 times, but it’s simpler to use a loop, which is a set of statements that executes repeatedly.
To create a loop, we can use the
for statement, like this:
for i=1:30 bike_update end
The first line includes what looks like an assignment statement, and it is like an assignment statement, except that it runs more than once. The first time, it creates the variable
i and assigns it the value 1. The second time,
i gets the value 2, and so on, up to and including 30.
The colon operator (
:) specifies a range of integers. You can create a range at the prompt:
>> 1:5 ans = 1 2 3 4 5
The variable you use in the
for statement is called the loop variable. It’s common to use the names
k as loop variables.
The statements inside the loop are called the body. By convention, they are indented to show that they’re inside the loop, but the indentation doesn’t affect the execution of the program. The
end statement marks the end of the loop.
To see a loop in action you can run one that displays the loop variable:
>> for i=1:5 i end i = 1 i = 2 i = 3 i = 4 i = 5
As this example shows, you can run a
for loop from the command line, but it’s more common to put it in a script.
Create a script named bikeloop.m that uses a
for loop to run bikeupdate.m 30 times. Before you run it, you have to assign values to
c. For this exercise, start with the values
b = 100 and
c = 100.
If everything goes smoothly, your script will display a long stream of numbers on the screen. It’s probably too long to fit, and even if it did fit, it would be hard to interpret. A graph would be much better!