nargin vs exist

前端 未结 6 2036
爱一瞬间的悲伤
爱一瞬间的悲伤 2020-12-30 06:46

Given a function like:

function foo(myParam)
if nargin<1
  myParam = \'default value\';
end % if
end % function

I\'ve seen people use so

6条回答
  •  醉话见心
    2020-12-30 07:18

    I'd go with the NARGIN option, for the reasons listed by SCFrench. One additional benefit: I often find myself using it in conjunction with a SWITCH statement when I have more than 2 input arguments:

    function outArgs = my_fcn(inArg1,inArg2,inArg3)
      switch nargin,
        case 0,  % No input case
          error('Not enough inputs!');
        case 1,  % Set last 2 inputs to default
          inArg2 = 'yes';
          inArg3 = 'on';
        case 2,  % Set last input to default
          inArg3 = 'on';
      end
      ...
      % Checking of variable types and values would go here! 
      ...
    end
    

提交回复
热议问题