Search code examples
matlabfunction-handle

Why does nargout return -1? And how to get the correct number of function outputs in that case?


Why does nargout return -1 in this case?

function test

fun=@(a)helper_fun(a,2);

[x,y]=fun(1);
x,  % 1
y,  % 2
nargout(fun),   % -1

end

function [c,d] = helper_fun(a,b)

c=a;
d=b;

end

Is there an alternative to extract the correct number of output variables of fun?

I was hoping to impose a syntax check in a function that takes function_handle as an optional variable and this artifact forced me to either change how my function must look or not check number of outputs.


Solution

  • From the documentation: nargout returns a negative value to mark the position of varargout in the function declaration. As an example, for a function declared as

    [y, varargout] = example_fun(x)
    

    nargout will give -2, meaning that the second "output" is actually varargout, which represents a comma-separated list that can contain any number of outputs.

    nargout gives -1 for anonymous functions because they can return any number of outputs. That is, their signature is equivalent to

    varargout = example_fun(x)
    

    How can an anonymous function return more than one output? As indicated here, by delegating the actual work to another function that can. For example:

    >> f = @(x) find(x);
    >> [a, b, c] = f([0 0 10; 20 0 0])
    a =
         2
         1
    b =
         1
         3
    c =
        20
        10
    >> nargout(f)
    ans =
        -1
    

    Compare this to

    >> f = @find;
    >> nargout(f)
    ans =
         3
    

    The result is now 3 because find is defined with (at most) 3 outputs.