Main Content

Loop Variables

The loop variable defines the loop index value for each iteration. You set it in the first line of a parfor statement.

parfor p=1:12

For values across all iterations, the loop variable must evaluate to ascending consecutive integers. Each iteration is independent of all others, and each has its own loop index value.

Required (static): Assignments to the loop variable are not allowed.

This restriction is required, because changing p in the parfor body cannot guarantee the independence of iterations.

This example attempts to modify the value of the loop variable p in the body of the loop, and thus is invalid.

parfor p = 1:n
    p = p + 1;
    a(p) = i;
end

Required (static): You cannot index or subscript the loop variable in any way.

This restriction is required, because referencing a field of a loop variable cannot guarantee the independence of iterations.

The following code attempts to reference a field (b) of the loop variable (p) as if it were a structure. Both lines within the loop are invalid.

parfor p = 1:n
    p.b = 3
    x(p) = fun(p.b)
end

Similarly, the following code is invalid because it attempts to index the loop variable as a 1-by-1 matrix:

parfor p = 1:n
    x = p(1)
end

See Also

Related Topics