Main Content

Use Objects and Handles in parfor-Loops

Objects

When you run a parfor-loop, you can send broadcast variables or sliced input variables from the client to workers, or send sliced output variables from workers back to the client. The save and load functions must be supported for each object that you send to or from workers. For more information, see Save and Load Process for Objects.

Assigning a value to the sliced property of an object or the sliced field of a structure is not supported in a parfor-loop.

InvalidValid
s = struct;
parfor i = 1:4
    s.SomeField(i) = i;
end
parfor i = 1:4
    x(i) = i;
end
s = struct('SomeField',x);

For more information about first-level indexing constraints, see Sliced Variables.

Handle Classes

You can send handle objects as inputs to the body of a parfor-loop. However, any changes that you make to handle objects on the workers during loop iterations are not automatically propagated back to the client. That is, changes made inside the loop are not automatically reflected after the loop.

To make the client reflect the changes after the loop, explicitly assign the modified handle objects to output variables of the parfor-loop. In the following example, maps is a sliced input/output variable.

maps = {containers.Map(),containers.Map(),containers.Map()}; 
parfor ii = 1:numel(maps)
    mymap = maps{ii};   % input slice assigned to local copy
    for jj = 1:1000
        mymap(num2str(jj)) = rand;
    end
    maps{ii} = mymap;   % modified local copy assigned to output slice
end

Sliced Variables Referencing Function Handles

You cannot directly call a function handle with the loop index as an input argument, because this variable cannot be distinguished from a sliced input variable. If you must call a function handle with the loop index variable as an argument, use feval.

The following example uses a function handle and a for-loop.

B = @sin;
for ii = 1:100
    A(ii) = B(ii);
end

A corresponding parfor-loop does not allow B to reference a function handle. As a workaround, use feval.

B = @sin;
parfor ii = 1:100
    A(ii) = feval(B,ii);
end

Related Topics