Search code examples
matlabparallel-processingparfor

parfor with nested for: variable classification depends on loop endVal


I want to compute a fractal image in two nested loops over the pixel indices (ix,iy). The sample code just assigns a random number to RGB values instead of the real calculations.

x = 0:.2:4;
y = 0:.2:3;
nX = length(x);
nY = length(y);
RenderRed = zeros(nX,nY); RenderGreen = zeros(nX,nY); RenderBlue = zeros(nX,nY);

parfor ix = 1:nX
    % for iy = 1:length(y)  % error
    for iy = 1:nY
        % "compute" pixel (ix,iy)
        RenderRed(ix, iy) = rand; RenderGreen(ix, iy) = rand; RenderBlue(ix, iy) = rand;
    end
end

Pctr = [];
Pctr(:,:,1)=RenderRed; Pctr(:,:,2)=RenderGreen; Pctr(:,:,3)=RenderBlue;
handle = image(Pctr);
shg

The code works as shown but if the end value of the iy loop is changed from nY to length(y) - see the commented line - an error is issued:

Error: The variable RenderRed in a parfor cannot be classified.
See Parallel for Loops in MATLAB, "Overview".

Why? In my understanding of sliced variables no version should work: one has to use an auxiliary variable collecting the results of the inner loop, and assign that to a slice of the matrix. But length(y) instead of nY should have no effect at all on the classification of variables because y is never assigned in the loops.

mlint finds no error, in neither version. Same behaviour with MATLAB versions 2016b, 2017b.


Solution

  • According to the Matlab documentation, this actually can work! When you want to use nested for loops inside parfor loops:

    For proper variable classification, you must define the range of a for-loop nested in a parfor-loop by constant numbers or variables.

    enter image description here