I have a code whose basic structure is that bellow. Because there are a lot of for loop iterations I was thinking to transform the for loop to parfor loop. Unfortunatelly, I am getting an error: The repmorary variable 'DeclaredVar' uses a value set outside the PARFOR
. Are there any techniques to overcome such problems?
t = ee; % save my data in t. t is a Nx1 vector
boolvar = 0;
parfor x=1:length(xs) % xs is a Mx1 vector (N>>M).
xx = xs(x);
t = t(t>=xx); %% the temporary variable 't' uses a value set outside the PARFOR loop
if boolvar==0 %% the temporary variable 'boolvar' uses a value set outside the PARFOR loop
try
% Part 1 code
catch
boolvar = 1;
end;
end;
if boolvar==1
% execute Part 2 code if boolvar is true
end;
M(x,:) = % save data. M is a length(xs) x 2 matrix
end
Thank you!
I tried to figure out what your code does. Please correct me if I'm wrong -
So you want to go through a vector xs
. Each time you pick out a value xx
from xs
, you filter the data t
by selecting only those t>xx
, and update t. Then, if the flag is down, do something, and raise the flag; if the flag is already up, do something else.
You have definitely 2 problems here which have been complained by Matlab.
t
gets updated in each loop, depending on its own value.
This won't hurt if you do it step by step. Consider a box of 20 numbered balls. You have a list of numbers say randperm(20)
.
In each iteration, you look up the number in the list, find the ball with that number, and remove it from the box, and finally record what's left in the box. It's easy.
But now consider you have 3 workers that will do the job for you. They are independent from each others and work at different, and randomly varying (eg depending on the weather and their moods), speeds. Each time they ask you for a number from the list, then do the above to the box, and tell you what's left inside. Repeat the same game 3 times. They result will not be the same, since the workers themselves - but not your data - have uncertainties.
boolvar
gets updated in each loop, only when it is false.
Again, to the workers, nothing strange, they just follow your instructions.
But to you (and Matlab), the final result will depend on the weather. This at least isn't allowed by Matlab's designers, who must dislike uncertainties.
The point is you cannot read or write the same variable in parallel process, because you cannot predict the outcome without uncertainties. See getting started with parfor
.
Variables used in parfor
should be categorized as one of "loop", "sliced", "broadcast", "reduction", and "temporary". See advanced topic for more details. The error you got says Matlab recognizes t
and boolvar
as temporary variables, as you assign it with values in the loop; but the loops also rely on values outside the parfor
loop.