以下代码应成功运行assert语句在Matlab2014b中传递,但在Matlab2015b中失败。
如何获取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

最佳答案

这就是我在Matlab2015B上所做的:

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

或者,在调用者中将nargin赋给变量(例如narg = nargin;),则可以使用:
evalin('caller','narg'); %// If you assigned the caller's nargin to "narg"

除此之外,检查函数输入并设置默认值的更常用方法是:
基于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

基于变量的逻辑:
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

有关更多想法,请参见this discussion
这是我用来测试不同选项的代码(将以下代码另存为exist):
function test_caller_nargin(varargin)

print_caller_nargin();

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

end

08-16 04:45