41

Say that I have a function, dummy, with 2 arguments. The arguments can have default values when not supplied in function call. But how do I know is an arguments is not supplied?

I know I can use nargin, like this

function dummy(arg1, arg2)
if nargin < 2
    arg2 = 0;
end
if nargin < 1
    arg1 = 0;
end
% function body

I want to know whether I can check whether an arguments is supplied based on the argument name? Something like supplied(arg2) == false.

I ask this because, sometimes I want to add new arguments at the front of the argument list (as it may not have a default value), and then I have to change all the if nargin .... If I can check by name, nothing has to be changed.

fefe
  • 3,342
  • 2
  • 23
  • 45

1 Answers1

71

I always do like that:

if ~exist('arg1','var')
  arg1=0;
end

As said by @Andrey, with this solution you can change the number/order of the arguments of the function, without changing the code. This is not the case with the nargin solution.

As said by @yuk, if you want to allow to skip arguments you can do:

if ~exist('arg1','var') || isempty(arg1)
  arg1=arg1DefaultValue;
end
Oli
  • 15,935
  • 7
  • 50
  • 66
  • 1
    This is much better than nargin, because you don't have to change the code in case you ever change the order of the parameters in the function. – Andrey Rubshtein Dec 21 '11 at 15:16
  • 1
    I usually also add `... | isempty(arg1)`, so user can skip `arg1`, but supply `arg2`. Of course if `arg1` cannot be empty. – yuk Dec 21 '11 at 16:56
  • 2
    Abosultely, but I thought it was not really answering the question. Anyway, I edited the answer, Also I think you have to use `||` (Short-Circuit Operator) to make sure there is no error if `arg1` does not exist. – Oli Dec 21 '11 at 19:53
  • 7
    Note that skipping here means supplying `[]` or `{}` in place of the argument, not the Visual Basic / VBScript style skipping, where one places multiple commas like this `f(,,a,,,a)`. – Evgeni Sergeev Mar 22 '13 at 03:16