Why is my variable not available inside a parfor loop?

14 views (last 30 days)
I've run into some behavior that I can't understand, In the following piece of code:
exist('srRays','var')
parfor ii=1:nr
exist('srRays','var')
str=etags{ii};
tf_localEvent = (str(1)=='L');
if tf_localEvent
[x{ii} y{ii} z{ii} d{ii} ttm(ii) itm(ii)] = fetchrayLocal(srGeometry, srModel, srRays, data.evt, iprec, etags{ii}, xsta, ysta);
else
[x{ii} y{ii} z{ii} d{ii} ttm(ii) itm(ii)] = fetchray(srtimes, srindex, etags(ii), BT2, iprec, srModel, xsta, ysta);
end
end
The variable 'srRays' is on the workspace before going into the parfor loop, but then inside the loop Matlab can't find it. So that in the line before the loop
exist('srRays','var')
results in
ans = 1
in the line inside the loop, it results in
ans = 0
and then I get an error when it tries to use it as an input to the function 'fetchrayLocal'. Does anybody know why my variable is disappearing? if it helps, srRays is a (1x1) structure, so are srGeometry and srModel.
Thanks,
Max
  3 Comments
Shayan Modiri
Shayan Modiri on 10 Oct 2012
This is true, you shouldn't use Global Variables in parfor loops. You can check this before parfor:
whos m
If you see Global in Attributes, it means this is a Global variable. You can easily copy this variable before your parfor to tmp_srRays and use this new variable in your parfor.
Jan
Jan on 11 Oct 2012
Slightly faster and nicer:
tf = strncmp(etags, 'L', 1);
parfor ii = 1:nr
if tf(ii)
...

Sign in to comment.

Answers (1)

Adel H
Adel H on 31 May 2019
We had a similar situation for variables we loaded from a .mat file.
As recommended by the troubleshooter, https://uk.mathworks.com/help/matlab/import_export/troubleshooting-loading-variables-within-a-function.html , we tried explicitly loading variable names.
However, that did not help.
What did fix the issue, was re-assigning these variables to themselves before the parfor loop. e.g:
subDegRes = subDegRes;
a2PLimit = a2PLimit;
a2P = a2P;

Categories

Find more on Parallel for-Loops (parfor) in Help Center and File Exchange

Tags

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!