for statement

The for statement is used to repeatedly execute a bunch of commands for a definite number of times. The often used form is as follows
    for var = k0 : k1
        statement group
    end
where var is a variable name, k0 and k1 are two expressions that should evaluate to two integers with k0<=k1. When the for statement is encountered, the variable var is set to k0, and if k0 is less than or equal to k1, the statement group is executed once. then the variable var is increased by 1. If var is still within k1, the statement group is executed again. This is repeated untill var exceeds k1. The loop counter var is a variable that can be accessed in the group of statements. It can be either a previously defined variable, or a new name. Inside the loop, the value of the counter is updated automatically, and therefore shouldn't be altered explicitly. Any assignment to the loop counter inside the loop is ignored. For example, the following code find the sum
    s = 0;
    n = 1000000;
    for k = 1 : n
        s += k;
    end

A second variant of the for statement

    for var = k0 : step : k1
        statement group
    end
In this case, the loop counter var receives values of k0, k0 + step, k0 + 2 * step, ..., until it's greater than k1 (if step is positive), or less than k1 (if step is negative).

Finally, there is a short form of for statement, in which the value of the counter is not needed in the loop, and the code is repeated for a given number of times.

    for n
         statement group
    end
where n should be an expression that evaluates to an integer, which is the number of times the statement group is going to be carried out.

The statement group of the for loop may contain simple statements or other control structures. For example,

    A = zeros(10, 10);
    for k = 1 : 10 
         for j = 1 : 10
             A[k, j] = k * j; 
         end
    end

oz 2009-12-22