nargin,vargin,存在,什么是实现可选参数的最佳方法matlab [英] nargin, vargin, exist, what is the best way to implement optional arguments matlab
问题描述
我在matlab中有一个功能:
I have a function in matlab:
function output = myfunc(a,b,c,d,e)
%a and b are mandetory
%c d and e are optional
end
如果用户给e而不是c和d给出了可选的arg,我将如何处理输入?
How would I handle inputs if a user gave an optional arg for e but not for c and d?
nargin仅给出参数的数量.会是最好的方法吗?
nargin just gives the number of arguments. would exist be the best way?
推荐答案
只需使用 nargin .它会告诉您有多少参数.仅当具有变量个参数时,即您对参数的数量没有限制,或者您希望以索引方式访问这些参数时,才使用varargin.我认为情况并非如此,因此一种解决方案可能看起来像这样.
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>
如果用户不想为c或d提供值,而是提供e,则必须通过[],例如 func(a,b,c,[],e),以省略d.
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.
或者,您可以使用
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个参数.
to check if all a arguments e are present. But this requires exactly 2 or 5 arguments.
这篇关于nargin,vargin,存在,什么是实现可选参数的最佳方法matlab的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!