MATLAB: variable progress is uninitialized temporary not reduction

1.3k views Asked by At

In a simple progress indicator, I update how much percent the loop has gone forward:

progress=0;
N=10;

for k=1:N
    % ....
    progress=progress+1;
    disp(sprintf('progress %d%%',progress/N*100));
end

And the output:

progress 10%

progress 20%

progress 30%

progress 40%

progress 50%

progress 60%

progress 70%

progress 80%

progress 90%

progress 100%

However, when I try to change the for loop into parfor (parallel loop), I face with an error

progress=0;
N=10;

parfor k=1:N
    % ....
    progress=progress+1;
    disp(sprintf('progress %d%%',progress/N*100));
end

Error using test (line 4)

Error: The variable progress is perhaps intended as a reduction variable, but is actually an uninitialized temporary.

See Parallel for Loops in MATLAB, "Temporary Variables Intended as Reduction Variables".

How to fix it?

1

There are 1 answers

2
Edric On

A reduction variable inside parfor cannot be read during the loop execution. Remember that all the iterations of the loop are conceptually happening simultaneously. MATLAB knows how to transform the expression

progress = progress + 1;

into something meaningful because of the precise form of that expression (i.e. it recognises the associative nature of the operation). There is no communication possible among the workers executing the body of the parfor loop, so there is no way to determine the overall value of progress until the loop has completed.

If you want to display progress in this way, you might wish to investigate using parfeval which allows you to submit work asynchronously to the workers, and monitor overall progress back at the client. Here's an example in the documentation.