parfor warning and analysis of switch statement

1 次查看(过去 30 天)
I have two functions which are, I think, functionally identical. Both use a parfor loop. If the logic within the loop is expressed using switch, I get a warning at run-time. If the same logic is expressed using if, there is no warning. The functions return the same result.
This seems like a bug, but I haven't used the Parallel Computing Toolbox much so I thought I'd ask whether anyone could shed any light on this behaviour before I send in a service request.
Here is the version using switch:
function op = parfortest1
t = 'xyz';
op = zeros(1, 10);
parfor kk = 1:10
switch t
case 'abc'
q = rand;
otherwise
q = -1;
end
op(kk) = q;
end
end
which generates this message:
Warning: File: parfortest1.m Line: 11 Column: 14
The temporary variable q will be cleared at the beginning of
each iteration of the parfor loop.
Any value assigned to it before the loop will be lost. If q
is used before it is assigned in the parfor loop, a runtime
error will occur.
And here is the if version, which does not produce the warning:
function op = parfortest2
t = 'xyz';
op = zeros(1, 10);
parfor kk = 1:10
if strcmp(t, 'abc')
q = rand;
else
q = -1;
end
op(kk) = q;
end
end
I can thus work round the problem - my question is whether I have missed some obvious, or unobvious but documented reason for the difference in behaviour, or whether this is a failure of the parser to correctly analyse the switch case and recognise that q is always given a value before it is used.

回答(1 个)

Sean de Wolski
Sean de Wolski 2015-5-28
It doesn't error does it? It looks like the warning is a feature of the switch statement letting you know what you can expect as behavior. You should be able to turn the warning off.
  1 个评论
David Young
David Young 2015-5-28
Thanks - yes, I can switch off the warning - at the expense of cluttering my code. But I suspect the warning should not be there, because q always receives a value before it is used, and the warning is being issued in error.

请先登录,再进行评论。

类别

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

标签

Community Treasure Hunt

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

Start Hunting!

Translated by