Search code examples
matlabfor-loopiterationparfor

MATLAB: parfor error


I have the following MATLAB code that I want to run it by using parfor:

max = -1;
for i = 1:10
    for j = (i+1):10
       X = my_function(i, j);
       if (X > max)
           max = X;
       end
    end
end
disp(max)

I want to change the first for to parfor. I read couple of tutorials and the documentation, but I don't know how to have the same result for max, by using parfor.

I know that there is some problem with the usage of i in for j = (i+1):10.

I would appreciate any suggestion.


Solution

  • You can not use parfor for dependent iterations, i.e. in your case max is a dependent (shared) variable between your loop iterations:

    You cannot use a parfor-loop when an iteration in your loop depends on the results of other iterations. Each iteration must be independent of all others.

    This is also reflected in the displayed warning message:

    Warning: The temporary variable max will be cleared at the beginning of each iteration of the parfor loop. Any value assigned to it before the loop will be lost. If max is used before it is assigned in the parfor loop, a runtime error will occur. See Parallel for Loops in MATLAB, "Temporary Variables".

    MATLAB implements one exception to this rule, i.e. Reduction Variables:

    The exception to this rule is to accumulate values in a loop using Reduction Variables.

    So, you can rewrite your code to use reduction variables:

    maxX = -1;
    for i = 1:10
        for j = (i+1):10
           maxX = max(maxX, my_function(i, j));
        end
    end
    disp(maxX)