Skip to main content

11.7) for...end Statement


"for" loops are used to repeat segments of code.

They are used when code needs to be repeated a fixed number of times. The syntax is as follows:

[matlab]
for i=start_value:end_value
statement
end
[/matlab]

"i" is the loop counter. On every iteration of the loop, the loop counter is incremented by 1. On the first pass, the loop counter will be set to "start_value". When the loop counter reaches the "end_value", the statement executes for the last time

The loop counter can be incremented by values other than one. This is termed the stride (or increment). If you don't want to use the default stride (1), then the syntax is:

[matlab]
for i=start_value:stride:end_value
statement
end
[/matlab]

Examples of the for...end construct:

[matlab]
>> n=10;
>> sum=0;
>> for i=1:n
>> sum=sum+i;
>> end
[/matlab]
[matlab]
>> n=100
>> sum=0
>> for i=1:2:100
>> sum=sum+i
>> end
[/matlab]
[matlab]
>> n=100;
>> s=0;
>> average=0;
>> v=rand(n,1);
>> for i=n:-1:1
>> s=s+v(i,1);
>> end
>> average=s/n;
[/matlab]