Search code examples
matlabparallel-processingparfor

Access variable in nested parfor loop in MATLAB


Consider the following code in MATLAB:

function parallelProblem
N = 10;
A = rand(N);
parfor i=1:N
    for k=2:N
        A(i,k) = f(A(i,k-1));
     end
end

end

function y=f(x)
y = x;
end

This is a summary of the problematic code I'm working on. Basically the idea is the following: I have to variables iand kand I can perform my computation with no communication between different i, but communication between different values of kis required.

Therefore I want to parallelize the loop over i. However, for the code above I get the error

parallelProblem

Error: File: parallelProblem.m Line: 6 Column: 9
The variable A in a parfor cannot be classified.
See Parallel for Loops in MATLAB, "Overview".

Hovering over the word parfor (which is underlined) gives

The PARFOR loop can not run due to the way the variable 'A' is used.

and hovering over f(A(i,k-1)) gives

Valid indices for 'A' are restricted in PARFOR loops

and

In PARFOR loop, variable 'A' is indexed in different ways, potentially causing dependencies between iterations.

From an intuitive point of view, I see no reason why the code should be working in parallel. Is there any way, I can modify my code to get the desired result?


Solution

  • The problem is that you are overwriting A. Loops in a parfor are not executed in order and MATLAB sees that you are overwriting the values of A, and then using them. You can easily fix this using an auxiliary variable:

    function parallelProblem
    
    N = 5;
    A = magic(N);
    Aresult=[];
    parfor i=1:N,N
        b=[];
        for k=2:N
            b(k) = f(A(i,k-1));
        end
       Aresult(i,:)=b;
    end
    
    end