inputParser/addOptional Error
24 views (last 30 days)
Show older comments
I am not able to understand the error in "addOptional" which I have illustrated below. Is the argname in addOptional not case-sensitive? Is there a way to change this setting? Moreover, in the code below, parameter b is a optional parameter dependent on the required value a (b=2a unluess a value of b is passed), is there a easier way to define that rather what I did below?
The following code
function S = test(varargin)
p = inputParser;
addRequired(p,'a',@isnumeric);
addOptional(p,'b',[],@isnumeric);
addOptional(p,'A',1,@isnumeric);
p.KeepUnmatched = true;
parse(p,varargin{:})
a = p.Results.a;
if isempty(p.Results.b)
b = 2*a;
end
A = p.Results.A;
S = a+b+A;
end
outputs the error:
Error using inputParser/addOptional
A parameter name equivalent to 'A' already exists in the input
parser. Redefining a parameter is not allowed.
Error in test (line 7)
addOptional(p,'A',1,@isnumeric);
while the one below works just fine:
function S = test(varargin)
p = inputParser;
addRequired(p,'a',@isnumeric);
addOptional(p,'b',[],@isnumeric);
addOptional(p,"c",1,@isnumeric);
p.KeepUnmatched = true;
parse(p,varargin{:})
a = p.Results.a;
if isempty(p.Results.b)
b = 2*a;
end
c = p.Results.c;
S = a+b+c;
end
0 Comments
Answers (1)
Pratyush
on 20 Oct 2023
Hi Sabhrant,
I understand that you are getting an error while using the “addOptional” function and are seeking an easire way to perform the task.
Please note that in MATLAB, the “addOptional” function in the “inputParser” class is ‘case-insensitive’ for the argument names. This means that if you try to add an optional argument with a name that is already defined (ignoring case), you will get an error.
To change this behavior and make the argument names case-sensitive, you can use the “addParameter” function instead of “addOptional”. The “addParameter” function was introduced in MATLAB R2013b and supports case-sensitive argument names. You refer to this documentation for more information: Add optional name-value pair argument into input parser scheme - MATLAB addParameter - MathWorks India
The following code snippet demonstrates the use of “addParameter”:
function S = test(varargin)
p = inputParser;
addRequired(p,'a',@isnumeric);
addOptional(p,'b',[],@isnumeric);
addParameter(p,'A',1,@isnumeric); % Use addParameter instead of addOptional
p.KeepUnmatched = true;
parse(p,varargin{:})
a = p.Results.a;
if isempty(p.Results.b)
b = 2*a;
else
b = p.Results.b;
end
A = p.Results.A;
S = a+b+A;
end
Hope this helps.
0 Comments
See Also
Categories
Find more on Function Creation in Help Center and File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!