Why is my variable not available inside a parfor loop?

2 Ansichten (letzte 30 Tage)
Max Bezada
Max Bezada am 17 Jul. 2012
Beantwortet: Adel H am 31 Mai 2019
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 Kommentare
Shayan Modiri
Shayan Modiri am 10 Okt. 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 am 11 Okt. 2012
Slightly faster and nicer:
tf = strncmp(etags, 'L', 1);
parfor ii = 1:nr
if tf(ii)
...

Melden Sie sich an, um zu kommentieren.

Antworten (1)

Adel H
Adel H am 31 Mai 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;

Kategorien

Mehr zu Loops and Conditional Statements finden Sie in Help Center und File Exchange

Tags

Community Treasure Hunt

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

Start Hunting!

Translated by