MATLAB: Function with unknown number of outputs within parfor

parallel computingparfor

Dear all,
I am facing this apparently simple problem: I am trying to write a parfor loop that containts a function call with an unknown number of output arguments. The way I tried to implement it is as follows
Tank=initialize_tank();
parfor ii=1:n
[outputs{:}]=myfunction(a,b,c,d);
Tank(:,ii)=outputs(:);
end
But due to the way variable outputs is used, I get a complaint from parfor. Does anybody know the workaround to this?
Thanks

Best Answer

The trick here is that (unfortunately) you need to assign the outputs of your function to a temporary variable, and convince parfor that the variable is indeed a temporary. Like so:
numOut = 3;
n = 7;
out = cell(numOut, n);
parfor idx = 1:n
% This line is required by PARFOR to ensure that 'tmp' is treated
% as a temporary loop variable:
tmp = cell(1, numOut);
% Call the function with a variable number of outputs:
[tmp{1:numOut}] = deal(rand());
% Assign into the output:
out(:, idx) = tmp;
end
Without the tmp = cell(1, numOut); statement, parfor thinks you are assigning to only part of tmp in the following line, and therefore concludes that your loop is order-dependent. By assigning to tmp without any indexing, parfor realises that you are creating a whole new value.