addParameter adds a Parameter/Value pair to the input syntax of your function. For example, if you had a function called myFunction in which you were using the input parser:

addRequired(p,'x')
addParameter(p,'Foo',1)

Would add:

myFunction(x,'Foo',value)

As a valid syntax with a default value of 1. In parameter value pairs, the name of the parameter is specified with a string or character array, followed by a value specification.

addOptional(p,'Foo',value)

Would add:

myFunction(x,value)

As an optional positional argument. In this case, you only specify the value of the optional argument without specifying a parameter name.

Answer from Alex Taylor on Stack Overflow
🌐
MathWorks
mathworks.com › simulink design optimization › sensitivity analysis
addParameter - Add parameter to sdo.ParameterSpace or sdo.GriddedSpace object - MATLAB
This MATLAB function adds the model parameters specified in p to an sdo.ParameterSpace or sdo.GriddedSpace parameter space and returns the updated parameter space.
🌐
MathWorks
mathworks.com › simulink › simulink environment fundamentals › programmatic model editing
add_param - Add parameter to Simulink model - MATLAB
This MATLAB function adds the specified parameters to the specified model and initializes the parameters to the specified values.
🌐
MathWorks
mathworks.com › deep learning toolbox › import and build deep neural networks › pretrained networks from external platforms
addParameter - Add parameter to ONNXParameters object - MATLAB
params = addParameter(params,name,value,type,NumDimensions) adds the network parameter specified by name, value, type, and NumDimensions to params.
Find elsewhere
🌐
MathWorks
mathworks.com › hdl coder › real-time hardware deployment › simulink real-time fpga i/o modules
hdlcoder.ReferenceDesign.addParameter - Add and define custom parameters for your reference design - MATLAB
This MATLAB function adds and defines a custom parameter for your reference design with a text box that displays the default value of the parameter.
🌐
MathWorks
mathworks.com › matlab › programming › functions › argument definitions
Parse Function Inputs - MATLAB & Simulink
Add inputs to the parsing scheme ... or addParameter. For optional inputs, specify default values. For each input, you can specify a handle to a validation function that checks the input and returns a scalar logical (true or false) or errors. The validation function can be an existing MATLAB ...
🌐
MathWorks
mathworks.com › matlab › programming › functions › argument definitions
inputParser - Input parser for functions - MATLAB
Use addOptional to add an individual argument into the input parser scheme. If you want to parse an optional name-value pair, then use the addParameter function. ... The inputParser function fully supports thread-based environments. For more information, see Run MATLAB Functions in Thread-Based ...
🌐
MathWorks
mathworks.com › simulink test
sltest.testmanager.TestCase.addParameterSet - Add parameter set - MATLAB
pset = addParameterSet(tc,Name,Value) adds a parameter set to the test case and returns a parameter set object, sltest.testmanager.ParameterSet.
🌐
MathWorks
mathworks.com › matlabcentral › answers › 266274-how-to-addparameter-and-validateattributes-for-several-values-at-once-oop
How to addParameter and validateattributes for several values at once (OOP)? - MATLAB Answers - MATLAB Central
February 2, 2016 - addParameter(parser,'PipeBolt',FilterObj.empty,@(x)validateattributes(x,'{FilterObj'},'PipeLineBolt','PipeBolt')) let say that FilterObj is Obj1 but for Obj1 (RotObj) how can I adjust the code to pass and validate atributes both types of objects? Sign in to comment. Sign in to answer this question. ... https://www.mathworks.com/matlabcentral/answers/266274-how-to-addparameter-and-validateattributes-for-several-values-at-once-oop#answer_1565670
🌐
Mit
lost-contact.mit.edu › afs › inf.ed.ac.uk › group › teaching › matlab-help › R2016b › matlab › ref › inputparser.addparameter.html
addParameter (inputParser)
addParameter(p,paramName,default) adds parameter name and value argument paramName to the input parser scheme of inputParser object, p.
🌐
MathWorks
mathworks.com › matlab › programming › functions › argument definitions
addOptional - Add optional, positional argument into input parser scheme - MATLAB
Use addOptional to add an individual argument into the input parser scheme. If you want to parse an optional name-value pair, then use the addParameter function. ... Run the command by entering it in the MATLAB Command Window.
Top answer
1 of 2
6

I do not recommended the use of inputParser with optional arguments that are allowed to be character arrays, because parse() cannot distinguish if the user passes a parameter name (which is always of type char) or the optional input argument. Thus, it is a logical consequence of this behaviour why you cannot pass a char as an optional input argument.

However, if you specify a validation function for the optional input arguments that may be char, you can make it work. From the addOptional documentation under section ‘Tips’:

For optional string inputs, specify a validation function. Without a validation function, the input parser interprets valid string inputs as invalid parameter names and throws an error.

This is the error your example generated.

Fixing your example

'o' is the optional input argument. If you know how to validate the values 'o' needs to accept, provide a validation function that returns true for those valid inputs. For example, if you know 'o' will always be a char array, try the following (line by line).

a = inputParser; 
addOptional(a, 'o', 'default', @ischar);
addParameter(a, 'p', 1);

parse(a, 'x');  % OK

parse(a, 'Hello, World!', 'p', 2);  % OK

parse(a, 'p', 'p', 'p')  % OK, although quite cryptic

parse(a, 3);  % Throws an error, as expected, because 3 is not a char

parse(a, 'p', 4)  % Throws a somewhat unexpected error, because we meant to set parameter 'p' to value 4

The last line seems counter-intuitive, but it's not! We'd expect the parser to detect the parameter 'p' instead of implicitly assuming it is the character we provide for optional argument 'o', which we wanted to omit. It is the expected behaviour, though, as I will explain now.

Why char optionals give inputParser a hard time

The demonstrated bahviour is expected because both the optional and parameter arguments are not required, i.e., optional. If you'd have two optional input arguments, 'o1' and 'o2', their order matters to the input parser (which is why the MATLAB documentation calls them ‘optional positional arguments’). You could never pass a value for 'o2' before a value for 'o1'. This implies 'o2' can only be used if 'o1' is also specified. In other words, 'o1' impedes the use of any other optional arguments.

The same is true for parameters, which should always come after other optional input arguments (as you already quoted). As such, they behave like optionals if any optional input arguments are allowed to be char. The result is MATLAB's inputParser not knowing if a char input is an optional input argument or a parameter. MATLAB's developers have decided to require explicit ordering of optional inputs, so MATLAB can be sure what optional arguments are passed to parse().

Suggested action if optional inputs may be char

Because using optional input arguments requires MATLAB to assume some input arguments referring to an optional input argument, others referring to parameters, this may result in errors, behaviour or results unexpected by the end-user if not all optional arguments are specified.

Input argument schemes are better if written explicitly to prevent this unexpected implicit behaviour. I suggest that if optional input arguments are required that accept char input, you always make them parameters, i.e., name-value pair arguments using addParameter. Using optional input arguments that accept char input only works if not using any parameters, or by explicitly stating (e.g. in the help) that parameter input argument can be used if and only if all optional input arguments are given as well.

2 of 2
1

The validation function of addOptional is used to determine if the parsed argument corresponds to the parameter specified with addOptional. If the validation function returns false, the current parsed argument is passed to the next addOptional/addParameter

The default validation function of addOptional is a simple ~ischar to distinguish between parameter and value due to performance reasons. See the answer of a TWM employee here. The provided solution however does not cover all use cases.

Below is a solution which works with any datatype, as well as with parameter/value structs. The only caveat: you cannot use a value which is equal to any parameter name.

a = inputParser;

% Validation function needs to check
% - if argument is a parameter name or a value
%   -> any(strcmp(x,a.Parameters))
% - if argument is a parameter/value struct
%   -> isstruct(x) && any(ismember(fieldnames(x),a.Parameters))
addOptional(a,'o','x',@(x)~(any(strcmp(x,a.Parameters)) || isstruct(x) && 
any(ismember(fieldnames(x),a.Parameters))));

addParameter(a, 'p', 1);

%The next three parse commands give all the same result struct

% 'o' as positional parameter
parse(a, 'w', 'p', 2)        

% 'o' as named parameter/value pair
parse(a, 'o', 'w', 'p', 2)   

% parameters provided as param/value struct
pv.o='w';
pv.p=2;
parse(a, pv)

% value of 'o' is a struct
data.x = 1;
parse(a, data)

%You cannot use a value equal to a parameter name
parse(a, 'p', 'p', 2) % FAIL

I suggest you to write a custom function for optional parameters if you don't mind the speed penalty

function addOptionalExt(parserObj,key,default)
parserObj.addOptional(key,default,...
    @(x)~(any(strcmp(x,parserObj.Parameters)) || ...
    isstruct(x) && any(ismember(fieldnames(x),parserObj.Parameters))));

and then use it in your example

a = inputParser;
addOptionalExt(a, 'o', 'x');
addParameter(a, 'p', 1);
parse(a, 'w', 'p', 2)
🌐
MathWorks
mathworks.com › simulink test
sltest.testmanager.ParameterSet.addParameterOverride - Add parameter override to parameter set - MATLAB
If ParamValue is a string scalar, it is evaluated as a MATLAB® expression when the test executes. ... Specify optional pairs of arguments as Name1=Value1,...,NameN=ValueN, where Name is the argument name and Value is the corresponding value. Name-value arguments must appear after other arguments, but the order of the pairs does not matter. Example: ovr = addParameterOverride(ps,a=2,BlockPath='myModel/Controller1')