false conditional still executed inside parfor

1 次查看(过去 30 天)
I have a function that takes multiple arguments, and if there's more than one argument, a parfor will have some extra code run accessing the extra inputs:
function x = myfunc(arg1,arg2,arg3)
parfor ...
if nargin > 1
arg1[i] = arg2[i];
end
%continue with other calcs
end %end of parfor
The problem is, even if nargin == 1, it appears that arg2[i] is still being accessed, for example. Is there a way to get around this problem?
This is in MATLAB 2011a for Linux if that makes a difference.

回答(1 个)

Edric Ellis
Edric Ellis 2013-5-22
The PARFOR machinery recognises arg2 as a sliced input variable to the loop, and sends the slices off to the workers - it cannot recognise the fact that you're not using it because the code analysis does not eliminate the body of your "if" block. You need either to write multiple PARFOR loops, or you may be able to concatenate together the args that you need. For example:
% assuming arg1 and arg2 are row vectors.
if nargin > 1
combinedArg = [arg1; arg2];
else
combinedArg = arg1;
end
parfor idx = ....
tmp = combinedArg(:, idx);
% Here, 'tmp' might be scalar, or 2x1
if nargin > 1
output(idx) = doStuff(tmp(1), tmp(2));
else
output(idx) = doStuff(tmp);
end
end

类别

Help CenterFile Exchange 中查找有关 Parallel for-Loops (parfor) 的更多信息

标签

Community Treasure Hunt

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

Start Hunting!

Translated by