MATLAB: Variable in a parfor cannot be classified

MATLABparfor classify variable

I'm attempting to convert some code to use a parfor, and have run into difficulty. A simplified example is given below, which doesn't work. I have read the documentation and lots of answers, but nonetheless can't seem to work it out.
% Preallocate array

var1 = zeros(5);
parfor i = 1:5
for j = 2:6
var1(j, :) = j;
end
end
Preallocating the arrays within the parfor gives no errors, but I don't understand why this works but the initial example doesn't. Could someone please put me out of my misery and explain this, or point me to the right bit of documentation? Thanks
parfor i = 1:5
% Preallocate array
var1 = zeros(5);
for j = 2:6
var1(j, :) = j;
end
end

Best Answer

In the second version, you are creating a local variable for use within the worker, whose value within the worker will be discarded and not returned to the client.
In the first version, you are creating a variable in the client and updating it in the worker, but every worker would be competing to update the same locations. In your particular case you can establish that the result would be the same as long as you used at least one worker, but consider the very slight modification:
var1 = zeros(5);
parfor i = 1:5
t = i;
for j = 2:6
var1(j, :) = j + t;
end
end
Now what would you expect the result to be? If you were using for instead of parfor you would recognize that you were overwriting all of rows 2 to 6 each time, and so the result would be the same as if you had executed only the last loop,
for i = 5
t = i;
for j = 2:6
var1(j,:) = j + t;
end
end
but with parfor the iterations can be done in any order and the workers would be competing to write to the same array. Iteration 2 might happen to be the last one to write to var1(5,3) but iteration 4 might happen to be the last one to write to var1(5,2) .
MATLAB does not permit this. You can only write to an output variable using the loop control variable. For example,
var1 = zeros(6,5);
parfor i = 1:5
t = i;
v1 = zeros(6,1);
for j = 2:6
v1(j,:) = j + t;
end
var1(:, i) = v1;
end