【问题标题】:nargin, vargin, exist, what is the best way to implement optional arguments matlabnargin,vargin,exist,什么是实现可选参数matlab的最佳方法
【发布时间】:2016-10-01 04:35:48
【问题描述】:

我在matlab中有一个函数:

function output = myfunc(a,b,c,d,e)
      %a and b are mandetory
      %c d and e are optional
end 

如果用户为 e 提供了可选的 arg 而不是为 c 和 d 提供了可选参数,我将如何处理输入?

nargin 只给出参数的数量。存在是最好的方式吗?

【问题讨论】:

  • 用户不能只提供第五个输入。您可以让他们为 cd 提供空值 [] 并检测到这一点。否则,也许可以考虑使用参数/值对。

标签: matlab


【解决方案1】:

只需使用 nargin。它会告诉你有多少参数存在。仅当您有 variable 数量的参数时才使用 varargin,也就是说,您的参数数量没有限制,或者您希望以索引方式访问参数。我认为您的情况并非如此,因此一种解决方案可能如下所示。

function output = myfunc(a,b,c,d,e)
  %a and b are mandetory
  %c d and e are optional
  if nargin < 3 || isempty(c)
     c = <default value for c>
  end
  if nargin < 4 || isempty(d)
     d = <default value for d>
  end
  if nargin < 5 || isempty(e)
     e = <default value for e>
  end
  <now do dome calculation using a to e>
  <If a or b is accessed here, but not provded by the caller an error is generated by MATLAB>

如果用户不想为 c 或 d 提供值但提供了 e,他必须传递 [],例如func(a,b,c,[],e), 省略 d。

你也可以使用

if nargin == 5
   <use a b c d and e>
elseif nargin == 2
   <use a and b>
else    
   error('two or five arguments required');
end

检查是否所有的参数 e 都存在。但这需要 2 或 5 个参数。

【讨论】:

    【解决方案2】:

    您可以将cde 定义为可选,然后根据位置分配值。如果他们想要e 而不是c,这需要空输入。例如:

    function output = myfunc( a, b, varargin )
    
    optionals = {0,0,0}; % placeholder for c d e with default values
    
    numInputs = nargin - 2; % a and b are required
    inputVar = 1;
    
    while numInputs > 0
        if ~isempty(varargin{inputVar})
            optionals{inputVar} = varargin{inputVar};
        end
        inputVar = inputVar + 1;
        numInputs = numInputs - 1;
    end
    
    c = optionals{1};
    d = optionals{2};
    e = optionals{3};
    
    output = a + b + c + d + e;
    

    这只会将所有内容加在一起。有很多错误检查需要发生。更好的方法可能是inputParser。这会进行配对输入和检查。见Input Parser help

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2010-09-21
      • 1970-01-01
      • 1970-01-01
      • 2010-09-09
      • 2015-08-21
      • 1970-01-01
      • 2022-08-16
      相关资源
      最近更新 更多