Resolve Issue: Array or Variable Access Pattern Not Suitable for Parallel Execution

Issue

A for loop is suitable for parallelization if the different loop iterations can be executed independently of each other without affecting the final answer. If one iteration of a for loop accesses data written in a different iteration, the iterations cannot be executed independently and the loop cannot be converted to a parallel loop. Suppose that your MATLAB® code contains such a loop and you set the configuration parameters EnableAutoParallelization and EnableAutoParallelizationReporting to true while generating code. In such situations, the code generator might produce this message in the Code Insights tab of the MATLAB Coder™ app or the code generation report:

Array or variable access pattern inside the loop is not suitable for parallel execution.

Possible Solutions

This code insights message might be triggered either by a scalar access pattern or by an array access pattern that causes an iteration of your for loop to depend on another iteration.

Check for Scalar Access Patterns

Suppose that your MATLAB code contains a loop that has a persistent scalar. This is an example of such a loop:

for i = 1:numel(x)
r = sqrt(y(i)) / x(i) * i;
y(i) = x(i) - r;
end

The variable r is persistent across loop iterations and prevents parallelization.

Eliminate the persistent scalar.  Removing the persistent scalar r enables the loop iterations to be executed independently. So, the serial loop can be converted to a parallel loop.

for i = 1:numel(x)
y(i) = x(i) - (sqrt(y(i)) / x(i) * i);
end

Convert the persistent scalar to a vector.  Converting the persistent scalar r to a vector r(i) enables the loop iterations to be executed independently. So, the serial loop can be converted to a parallel loop.

for i = 1:numel(x)
r(i) = sqrt(y(i)) / x(i) * i;
y(i) = x(i) - r(i);
end

Check for Array Access Patterns

Suppose that your MATLAB code contains a loop whose one iteration accesses data written in another iteration. This is an example of such a loop:

for i = 2:n
a(i) = a(i+1)
b(i) = b(i-1)
end
• The location a(i) that is written in the current iteration i was read in the previous iteration i-1.

• The location b(i) that is written in the current iteration i is read in the next iteration i+1.

If the loop is parallelized, such memory access order is not be preserved because every iteration can potentially be executed in parallel. So, the code generator does not automatically parallelize this loop.

To address this issue, try to rewrite your code to avoid such array access patterns. 