3
votes

What is the difference between addOptional and addParameter in MATLAB for creating functions?

MATLAB documention of these two functions:

addOptional(p,argName,default) adds optional input, argName, to the input parser scheme of inputParser object, p. When the inputs that you are checking do not include a value for this optional input, the input parser assigns the default value to the input.

addOptional(p,argName,default,validationFcn) specifies a validation function for the input argument.

addParameter(p,paramName,default) adds parameter name and value argument paramName to the input parser scheme of inputParser object, p. When the inputs that you are checking do not include a value for this optional parameter, the input parser assigns the default value.

addParameter(p,paramName,default,validationFcn) specifies a validation function for the input argument.

1
Parameters consist of a name-value-pair, i.e. you pass first a string defining the name of the parameter and then its value. Parameters come after the other arguments, but otherwise their order does not matter. addOptional refers to an input argument, i.e. a variable that you pass to a function. Both "functions" are in fact methods of the input parser class. Typically, you use that class within a function and pass it the function inputs you want to parse. You parse the inputs - souty

1 Answers

4
votes

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.