How to check whether an argument is supplied in function call?
Asked Answered
L

1

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.

Lacunar answered 21/12, 2011 at 13:22 Comment(0)
A
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
Aghast answered 21/12, 2011 at 13:48 Comment(4)
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.Inadvertent
I usually also add ... | isempty(arg1), so user can skip arg1, but supply arg2. Of course if arg1 cannot be empty.Shove
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.Aghast
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).Perot

© 2022 - 2024 — McMap. All rights reserved.