MATLAB: How to get the number of output arguments for a MATLAB expression

MATLAB

Hello folks, I have to evaluate multiple expressions in loop. Suppose x and y are one dimensional vectors and below three operations are supposed to be performed.
1) min(x)
2) min(x) + min(y)
3) min(x+min(y))
I am using eval for evaluating these expressions.
for count = 1:3
[output,index] = eval(fun(count));
end
In case 1 and 3, I need the value of expression and index as eval command sends both. But in case 2, I wont get index with eval and it throws error.
[a,b] = min(x) + min(y)
Error using +
Too many output arguments.
So in order to generalize, is there any possible way to know in advance that the expression is going to send one or two output arguments?

Best Answer

"So in order to generalize, is there any possible way to know in advance that the expression is going to send one or two output arguments?"
How would you then call those functions with one, and those with two outputs? It would be possible by allocating a cell array and using a comma-separated list, or by using some incomprehensible eval-based code, but really either of those is going to ugly spaghetti code.
A much simpler solution would be to use a try and catch:
C = {@(x,y)min(x), @(x,y)min(x)+min(y), @(x,y) min(x+min(y))};
x = 4;
y = 3;
for k = 1:numel(C)
try
[out,idx] = C{k}(x,y)
catch
out = C{k}(x,y)
end
end
which works without error, and does not use ugly eval. Or you with Mfiles could use nargout, e.g.:
for k = 1:numel(C)
n = nargout(C{k});
out = cell(1,n);
[out{:}] = C{k}(x,y)
end