mini-example:
function varargout = wrapper(varargin) varargout = someFunction(varargin);
That's how I'd do it first. But for example if someFunction = ndgrid
this yields a not defined for cell arrays error, so the next try was using someFunction(varargin{:})
instead. That's a successful call, but calling [a,b] = wrapper([1,2], [3,4])
does not yield the same result as a direct call to ndgrid
, so what am I doing wrong?
Description. varargin is an input variable in a function definition statement that enables the function to accept any number of input arguments. Specify varargin by using lowercase characters. After any explicitly declared inputs, include varargin as the last input argument .
Specify varargout using lowercase characters, and include it as the last output argument after any explicitly declared outputs. When the function executes, varargout is a 1-by-N cell array, where N is the number of outputs requested after the explicitly declared outputs.
nargin returns the number of function input arguments given in the call to the currently executing function. Use this syntax in the body of a function only.
Actually, Mikhail's answer is not quite right. In the case that someFunction is a function that returns a value even if none is requested, which is how a function indicates that the value should be assigned to ans, Mikhail's wrapper will fail. For example, if someFunction were replaced with sin and you compared running wrapper versus running sin directly, you'd see:
>> wrapper(0) >> sin(0) ans = 0
The right way to do this is
function varargout = wrapper( varargin ) [varargout{1:nargout}] = someFunction( varargin{:} );
The reason this works is due to a little known edge case in MATLAB indexing rules that has existed precisely for this case since at least R2006a (probably longer). It is something of a wart in MATLAB indexing but was deemed necessary to handle this sort of thing.
The rule is:
When performing subscripted assignment, if
Then the uninitialized variable is assigned a scalar cell containing the value returned by the right-hand side.
For example:
>> clear uninit % just to make sure uninit is uninitialized >> [uninit{[]}] = sin(0) uninit = [0]
function varargout = wrapper( varargin ) if ~nargout someFunction( varargin{:} ); else [varargout{1:nargout}] = someFunction( varargin{:} ); end
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With