Alex Rivera | Logout

nargin vs exist

Asked 2009-04-09T10:31:40.553
12

Given a function like:

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

I've seen people use something like the following in the place of the nargin version

if ~exist('myParam', 'var')
  myParam = 'default value';
end %if

I'm wondering if there is any preference either way?

The "~exist..." version to me has the advantage that if I change the order of my function parameters then it should still work. However my concern with this approach is that I might inadvertently pick up variables that are defined globally or in the scope of a surrounding function in the case of nested functions.

Any thoughts on the issue?

Edit
Report

1 Answer

4

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
answered 2009-04-09T14:08:27.663

Your Answer