Robin D.
Robin D.

Reputation: 39

How to get the number of arguments of the caller function in Matlab2015b?

The below code should run successfully. The assert statement passes in Matlab2014b, but fails in Matlab2015b.

How would you get the number of arguments for the caller function in Matlab2015b?

function test()
    fnA(1);
end

function fnA(A1, A2)
    n = nargin;
    fnB(1, 2);
    assert(n==A2, '%d does not equal %d', n, A2);
end

function fnB(B1, B2)
    n = evalin('caller', 'nargin');
    assignin('caller', 'A2', n);
end

Upvotes: 3

Views: 181

Answers (1)

Dev-iL
Dev-iL

Reputation: 24179

This is what I managed to do on MATLAB 2015b:

evalin('caller','numel(varargin)'); %// If you are/don't mind using varargin @ caller

Alternatively, in the caller assign nargin to a variable (e.g. narg = nargin;), then you can use:

evalin('caller','narg'); %// If you assigned the caller's nargin to "narg"

Other than that, the more commonly used methods to check your functions' inputs and set defaults are:

  1. Logic based on nargin:

    function test_func1(arg1, arg2, arg3)
      if nargin < 3 %// 2, 1 or 0
        arg3 = default_val_3;
      end
      if nargin < 2 %// 1 or 0
        arg2 = default_val_2;
      end
      if ~nargin %// same as nargin==0
        arg1 = default_val_1;
      end
      ... // rest of your code
    end
    
  2. Logic based on exist-ence of variables:

    function test_func1(arg1, arg2, arg3)
      if ~exist('arg3','var'), arg3 = default_val_3; end
      if ~exist('arg2','var'), arg2 = default_val_2; end
      if ~exist('arg1','var'), arg1 = default_val_1; end
      ... // rest of your code
    end
    
  3. See this discussion for more ideas.


This is what I used to test different options (save the following code as test_caller_nargin.m):

function test_caller_nargin(varargin)

print_caller_nargin();

function print_caller_nargin
  evalin('caller','numel(varargin)')
end

end

Upvotes: 3

Related Questions