Why is my variable not available inside a parfor loop?

2 ビュー (過去 30 日間)
Max Bezada
Max Bezada 2012 年 7 月 17 日
回答済み: Adel H 2019 年 5 月 31 日
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 件のコメント
Shayan Modiri
Shayan Modiri 2012 年 10 月 10 日
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 2012 年 10 月 11 日
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;

カテゴリ

Help Center および File ExchangeLoops and Conditional Statements についてさらに検索

タグ

Community Treasure Hunt

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

Start Hunting!

Translated by