The for-statement

Repeating the same operation over and over again is called iterating. One way to iterate when programming is to use a for statement. A for statement in its simplest form uses a variable representing an index that is increased by 1 in each step.

image

In the picture to the right the the index is called i. The command between for and end is repeated 10 times. The first time row 2 is executed, i is equal to 0, the second time i is equal to 1, and so on.

Row 4 starts with a %-sign, everything to the right of the %-sign is ignored when the program is run; this is a comment intended for those reading the actual code.

You can increment your index with something else than 1 by adding a number between the starting index and the last index.

1 for i=0:0.1:2
2     disp(i)
3 end
4 %21 numbers are displayed, the numbers 0,0.1,0.2,...,2

The recording below shows various features of the for statement.

by Malin Christersson under a Creative Commons Attribution-Noncommercial-Share Alike 2.5 Sweden License