addOptional

Adds an optional positional argument to an inputParser.

Category: Programming > Functions

Syntax

addOptional(p, name, default)

Declares an optional argument with a default value.

addOptional(p, name, default, validationFcn)

Also validates the value.

Description

Optional arguments follow the required ones and are matched by position. When the call has a value at that position, parse checks it with the validation function. A text value that matches the name of a declared parameter is not taken as the optional argument: it starts the name-value pairs and the optional keeps its default.

Omitted optionals appear in p.UsingDefaults.

Input arguments

p
An inputParser object.
name
Argument name, as text.
default
Value used when the argument is omitted.
validationFcn
Handle to a function that returns true for a valid value, or errors.

Example

Default and supplied values

p = inputParser;
addRequired(p, 'x');
addOptional(p, 'mode', 'fast', @ischar);
parse(p, 1);
p.Results.mode
parse(p, 1, 'slow');
p.Results.mode
p.UsingDefaults
Output
ans = 'fast'
ans = 'slow'
ans =

  0×0 empty cell array

See also

inputParser addRequired addParameter validatestring