MATLAB: How to capture an unknown number of output arguments in a cell array in MATLAB 7.5 (R2007b)

argumentsMATLABnargoutoutputvarargoutvariable

I have a function 'foo' and I do not know how many arguments it takes. I want to capture all output arguments of 'foo' in a cell array. I would like to know how to do that without having to guess the number of output arguments.

Best Answer

To determine the number of output arguments for a given function FOO use the NARGOUT function:
nargout('foo')
If the function has a variable number of input arguments, NARGOUT returns a negative value. You can call NARGOUT with the name of a function, or the name of Function Handles that map to specific functions.
For example, for the following function definition:
function [a b c d] = foo()
a = 'albert';
b = 'barry';
c = 'charlie';
d = 'david';
The following command:
nargout('foo')
returns 4.
If a function handle is defined as:
myhandle=@foo
The following command will also return 4:
nargout(myhandle)
For more information about NARGOUT execute the following in the MATLAB command prompt:
doc nargout
Once the number of output arguments is known, you can write the arguments into a cell array as follows:
% allocate a cell array
mycell=cell(1,nargout('foo'));
% the first part of the string inside the square brackets:
str='mycell{1}';
% on each i-th step in the loop add another mycell{i} to the string 'str'
for i=2:nargout('foo')
s=[' mycell{' int2str(i) '}'];
str=strcat(str,s);
end
% add the square brackets
str=['[' str ']'];
% use EVALC function to evaluate the complete expression:
T=evalc([str '=foo()']);
T = evalc(S) is the same as eval(S) except that anything that would normally be written to the command window, except for error messages, is captured and returned in the character array T (lines in T are separated by \n characters).
For more information on the EVAL function, execute the following in the MATLAB command prompt:
doc eval