开发者

uncertain number of inputs for my function

I recently came to a problem that I was supposed to define a function with uncertain number of inputs, that is, the number of inputs may vary depending on the practical context. Should I take use of a 2-D array or something else? I don't know if struct2cell helps and how if it really works.

Does anyone have an idea of the best way to go about doing开发者_开发知识库 this?

I've probably not been very clear, so please let me know if anything needs clarifying.

Thanks


There are several ways to go about this:

Use optional input arguments if a given parameter means the same regardless of context, but if in some scenarios, additional input is needed.

function out = myFun(first,second,third,fourth)

%# first is always needed
if nargin < 1 || isempty(first)
error('need nonempty first input')
end

%# second is optional
if nargin < 2 || isempty(second)
second = defaultValueForSecondWhichCanBeEmpty;
end

%# etc

You can call this function as out = myFun(1,[],2,3), i.e. pass an empty array for non-needed inputs.


If two inputs mean that the function is used one way, and three inputs mean that the function is used in another way (and even the inputs mean different things), use VARARGIN

function out = myFun(varargin)

%# if 2 inputs, it's scenario 1, with 3 it's scenario 2
switch nargin
case 2
   firstParameter = varargin{1};
   secondParameter = varargin{2};
   scenario = 1;
case 3
   firstParameter = varargin{1}; %# etc
otherwise
   error('myFun is only defined for two or three inputs')
end

Finally, you can also have your inputs passed as parameterName/parameterValue pairs. See for example this question on how to handle such input.


You can use nargin to validate the parameters to your function, so If you need only one do some action, or if tou pass more parameters do some other action. etc.. like:

function yours(arg1,arg2,arg3,arg4,arg5,...,argn)
  if nargin < 5
    arg5 =  'Init'
  elseif (nargin > 1)
    arg2 =  'Init'
    arg3 =  'Init'
    arg4 =  'Init'
    arg5 =  'Init'
   end
end

So you can control the number of parameters you receive.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜