Reputation: 1811
I have a function in matlab:
function output = myfunc(a,b,c,d,e)
%a and b are mandetory
%c d and e are optional
end
How would I handle inputs if a user gave an optional arg for e but not for c and d?
nargin just gives the number of arguments. would exist be the best way?
Upvotes: 5
Views: 5606
Reputation: 6085
Just use nargin. It will tell you how many arguments are present. Use varargin only when you have a variable number of arguments, that is you have no limit in number of arguments, or you want to access the arguments in an indexing fashion. I assume this is not the case for you, so one solution might look like this.
function output = myfunc(a,b,c,d,e)
%a and b are mandetory
%c d and e are optional
if nargin < 3 || isempty(c)
c = <default value for c>
end
if nargin < 4 || isempty(d)
d = <default value for d>
end
if nargin < 5 || isempty(e)
e = <default value for e>
end
<now do dome calculation using a to e>
<If a or b is accessed here, but not provded by the caller an error is generated by MATLAB>
If the user does not want to provide a value for c or d but provides e, he has to pass [], e.g. func(a,b,c,[],e), to omit d.
Alternatively you could use
if nargin == 5
<use a b c d and e>
elseif nargin == 2
<use a and b>
else
error('two or five arguments required');
end
to check if all a arguments e are present. But this requires exactly 2 or 5 arguments.
Upvotes: 2
Reputation: 2802
You can to define c
, d
and e
as optional and then assign values based on position. This requires empty inputs if they want e
but not c
. For example:
function output = myfunc( a, b, varargin )
optionals = {0,0,0}; % placeholder for c d e with default values
numInputs = nargin - 2; % a and b are required
inputVar = 1;
while numInputs > 0
if ~isempty(varargin{inputVar})
optionals{inputVar} = varargin{inputVar};
end
inputVar = inputVar + 1;
numInputs = numInputs - 1;
end
c = optionals{1};
d = optionals{2};
e = optionals{3};
output = a + b + c + d + e;
This will just add everything together. There is alot of error checking that needs to happen with this. A better approach might be inputParser
. This does paired inputs and checking. See Input Parser help
Upvotes: 1