Main Content

Broadcast Variables

A broadcast variable is any variable, other than the loop variable or a sliced variable, that does not change inside a loop. At the start of a parfor-loop, MATLAB® sends the values of any broadcast variables to all the workers. In this example, MATLAB sends the values of A and B to all the workers.

A = 5;
B = 10;
C = 0;
parfor i = 1:10
    if i == A
        C = C + B;
    end
end

Performance Considerations

Having large broadcast variables or many broadcast variables can cause significant communication between a client and its associated workers and increase overhead. Where communication overhead due to broadcast variables is large, consider creating and assigning temporary variables inside the loop instead. Conversely, where computational overhead due to creating and assigning temporary variables is large, consider using broadcast variables instead.

For more details, see Temporary Variables and Deciding When to Use parfor.

Note

When multiple parfor-loops need to access the same constant set of data, you can improve the performance of your code by using parallel.pool.Constant which transfers data to the workers only once instead of at the start of each parfor-loop.

To improve the performance of your code, look for opportunities to reduce the number of unnecessary broadcast variables. For example, this code contains a broadcast variable M.

M = magic(10);
parfor i = 1:numel(M)
    out(i) = M(i)./numel(M);
end

This code can be rewritten to evaluate numel(M) before the parfor-loop. Removing numel(M) from the parfor-loop prevents MATLAB from sending all elements of M to each worker. Instead MATLAB sends the value of N and a subset of the sliced variable M to each worker.

M = magic(10);
N = numel(M);
parfor i = 1:N
    out(i) = M(i)./N;
end

See Also

Related Topics