How to check if an argument is included in a function call?

Say I have a dummy function with two arguments. Arguments can have default values ​​if they are not included in the function call. But how do I know arguments are not provided?

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 if I can check if arguments are provided based on the argument name? Something like supplied(arg2) == false .

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

+31
matlab
Dec 21 '11 at 13:22
source share
1 answer

I always do this:

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

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

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

 if ~exist('arg1','var') || isempty(arg1) arg1=arg1DefaultValue; end 
+51
Dec 21 '11 at 1:48
source share



All Articles