nargin,vargin,exist,实现可选参数matlab的最佳方法是什么

use*_*664 5 matlab

我在matlab中有一个函数:

function output = myfunc(a,b,c,d,e)
      %a and b are mandetory
      %c d and e are optional
end 
Run Code Online (Sandbox Code Playgroud)

如果用户为 e 提供了可选参数但没有为 c 和 d 提供了可选参数,我将如何处理输入?

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

And*_* H. 2

Just use nargin. It will tell you how many arguments are present. Use varargin only when you have a variable number of arguments, that is you have no limit in number of arguments, or you want to access the arguments in an indexing fashion. I assume this is not the case for you, so one solution might look like this.

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>
Run Code Online (Sandbox Code Playgroud)

If the user does not want to provide a value for c or d but provides e, he has to pass [], e.g. func(a,b,c,[],e), to omit d.

Alternatively you could use

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
Run Code Online (Sandbox Code Playgroud)

to check if all a arguments e are present. But this requires exactly 2 or 5 arguments.