Why is my variable not available inside a parfor loop?

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

Is srRays a global variable? Global variables are not communicated to workers.
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.
Slightly faster and nicer:
tf = strncmp(etags, 'L', 1);
parfor ii = 1:nr
if tf(ii)
...

댓글을 달려면 로그인하십시오.

답변 (1개)

Adel H
Adel H 2019년 5월 31일
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;

카테고리

도움말 센터File Exchange에서 Loops and Conditional Statements에 대해 자세히 알아보기

태그

질문:

2012년 7월 17일

답변:

2019년 5월 31일

Community Treasure Hunt

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

Start Hunting!

Translated by