Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
319 views
in Technique[技术] by (71.8m points)

matlab - How to check whether an argument is supplied in function call?

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.

question from:https://stackoverflow.com/questions/8590478/how-to-check-whether-an-argument-is-supplied-in-function-call

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...