Why is my variable not available inside a parfor loop?
2 次查看(过去 30 天)
显示 更早的评论
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
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
2012-10-11
Slightly faster and nicer:
tf = strncmp(etags, 'L', 1);
parfor ii = 1:nr
if tf(ii)
...
回答(1 个)
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;
0 个评论
另请参阅
类别
在 Help Center 和 File Exchange 中查找有关 Loops and Conditional Statements 的更多信息
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!