Variable handling problem with parfor

1 次查看(过去 30 天)
I had some code that involved a for loop and variables, approximately thus:
if ~isempty(iList)
d = iList(k);
end
parfor s = 1:maxS
% various lines of code
if exist('d', 'var')
iString = num2str(d);
else
iString = 'blah-blah';
end
% various other lines of code
end
if exist('d', 'var')
iLegend = cellstr(num2str(iList'));
else
iLegend = 'blah-de-blah';
end
iList is set to empty [] when the function that contains this code is called. So the variable d doesn't exist anywhere in the code.
Before I converted this code to run with parfor, the regular for loop and the whole function/script ran without errors. Now, it errors-out and reports: "Unrecognized function or variable 'd'."
I don't understand why there is a problem. Since I can't debug the parfor parallelization, I don't have any more specifics - does the error come from within the loop or outside it, etc? Please help me identify. I am unaccustomed to working with parallelization and have been having some trouble with uninitialized temporaries, sliced structures, temporary variables that are not initialized outside the loop, not used after the loop, etc. I did manage to modify the code enough that no static errors were reported, but obviously there is still some runtime error.

采纳的回答

Matt J
Matt J 2023-8-4
编辑:Matt J 2023-8-4
I would try as below. This will be faster than your original version anyway, even before the conversion from for to parfor.
if ~isempty(iList)
d = iList(k);
else
d=[];
end
parfor s = 1:maxS
% various lines of code
if ~isempty(d)
iString = num2str(d);
else
iString = 'blah-blah';
end
% various other lines of code
end
  1 个评论
AR
AR 2023-8-6
Thanks - that worked. I don't know why the non-existence of the variable is a problem, though. Regardless, the problem is solved.

请先登录,再进行评论。

更多回答(0 个)

类别

Help CenterFile Exchange 中查找有关 Loops and Conditional Statements 的更多信息

产品


版本

R2023a

Community Treasure Hunt

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

Start Hunting!

Translated by