Variables in parfor-Loops

Unambiguous Variable Names

If you use a name that MATLAB cannot unambiguously distinguish as a variable inside a parfor-loop, at parse time MATLAB assumes you are referencing a function. Then at run-time, if the function cannot be found, MATLAB generates an error. (See Variable Names in the MATLAB® documentation.) For example, in the following code f(5) could refer either to the fifth element of an array named f, or to a function named f with an argument of 5. If f is not clearly defined as a variable in the code, MATLAB looks for the function f on the path when the code runs.

parfor i = 1:n
   ...
   a = f(5);
   ...
end

Structure Arrays in parfor-Loops

Creating Structures as Temporaries

You cannot create a structure in a parfor-loop by using dot-notation assignment. For example, in the following code both lines inside the loop generate a classification error.

parfor i = 1:4
   temp.myfield1 = rand();
   temp.myfield2 = i;
end 

The workaround is to use the struct function to create the structure in the loop, or at least to create the first field. The following code shows two such solutions.

parfor i = 1:4
    temp = struct();
    temp.myfield1 = rand();
    temp.myfield2 = i;
end 
parfor i = 1:4
    temp = struct('myfield1',rand(),'myfield2',i);
end

Slicing Structure Fields

You cannot use structure fields as sliced input or output arrays in a parfor-loop; that is, you cannot use the loop variable to index the elements of a structure field. For example, in the following code both lines in the loop generate a classification error because of the indexing:

parfor i = 1:4
    outputData.outArray1(i) = 1/i;
    outputData.outArray2(i) = i^2;
end 

The workaround for sliced output is to employ separate sliced arrays in the loop, and assign the structure fields after the loop is complete, as shown in the following code.

parfor i = 1:4
    outArray1(i) = 1/i;
    outArray2(i) = i^2;
end
outputData = struct('outArray1',outArray1,'outArray2',outArray2); 

The workaround for sliced input is to assign the structure field to a separate array before the loop, and use that new array for the sliced input.

inArray1 = inputData.inArray1;
inArray2 = inputData.inArray2;
parfor i = 1:4
    temp1 = inArray1(i);
    temp2 = inArray2(i);
end

Scalar Expansion with Sliced Outputs

You cannot use scalar expansion to define a set of values assigned to a sliced output array. For example, the following code attempts to expand the value idx for assignment to each element of the vector defined by x(:,idx); this generates an error.

x = zeros(10,12);
parfor idx = 1:12
  x(:,idx) = idx;
end

The following code offers a suggested workaround for this limitation.

x = zeros(10,12);
parfor idx = 1:12
   x(:,idx) = repmat(idx,10,1);
end

Global and Persistent Variables

The body of a parfor-loop cannot contain global or persistent variable declarations.

More About

Was this topic helpful?