inputParser class

Parse function inputs

Description

The inputParser object allows you to manage inputs to a function by creating an input scheme. To check the input, you can define validation functions for required arguments, optional arguments, and name-value pair arguments. Optionally, you can set properties to adjust the parsing behavior, such as handling case sensitivity, structure array inputs, and inputs that are not in the input scheme.

After calling the parse method to parse the inputs, the inputParser saves names and values of inputs that match the input scheme (stored in Results), names of inputs that are not passed to the function and, therefore, are assigned default values (stored in UsingDefaults), and names and values of inputs that do not match the input scheme (stored in Unmatched).

Construction

p = inputParser creates inputParser object p.

Properties

CaseSensitive

Scalar logical value that indicates whether to match case when checking argument names.

Possible values:

false (0)

Names are not sensitive to case: 'a' matches 'A'.

true (1)

Names are case sensitive: 'a' does not match 'A'.

Default: false

FunctionName

String that specifies the name of the function to include in error messages. By specifying the FunctionName, the parse method of the inputParser will throw error messages as if it were that function. This allows the error to be attributed to the correct function and allows easy access to function documentation through the error message.

Default: The default value is an empty string, ''.

KeepUnmatched

Scalar logical value that indicates how to handle parameter name and value inputs that are not in the input scheme.

Possible values:

false (0)

Throw an error whenever inputs are not in the scheme.

true (1)

Store the parameter names and values of unmatched inputs in the Unmatched property of the inputParser object, and suppress the error.

Default: false

PartialMatching

Scalar logical value that indicates whether partial matching of parameter names will be accepted. Partial parameter matching is supported by the addParameter method. If the value of StructExpand is true, then PartialMatching is not supported for structure field names corresponding to input parameter names.

Possible values:

true (1)

Inputs that are leading substrings of parameter names will be accepted and the value matched to that parameter. If there are multiple possible matches to the input string, MATLAB® throws an error.

false (0)

Input names are required to match a parameter name exactly (with respect to the CaseSensitive property.)

Default: true

StructExpand

Scalar logical value that specifies whether to interpret a structure array as a single input or as a set of parameter name and value pairs.

true (1)

Expand structures into separate inputs. Each field name corresponds to an input parameter name.

false (0)

Regard a structure array as a single input argument.

Default: true

Read Only Properties

Parameters

Cell array of strings that contains the names of arguments currently defined in the input scheme.

Each method that adds an input argument to the scheme (addRequired, addOptional, addParameter) updates the Parameters property.

Results

Structure containing names and values of inputs that match the function input scheme, populated by the parse method.

Each field of the Results structure corresponds to the name of an input.

Unmatched

Structure array containing the names and values of inputs that do not match the function input scheme, populated by the parse method.

If KeepUnmatched is false (default) or all inputs match the scheme, then Unmatched is a 1-by-1 structure with no fields. Otherwise, each field of the structure corresponds to the name of an input that did not match the scheme.

UsingDefaults

Cell array containing the names of inputs not passed explicitly to the function and assigned default values, populated by the parse method.

Methods

addOptionalAdd optional positional argument to input parser scheme
addParameterAdd optional parameter name-value pair argument to input parser scheme
addParamValue(Not recommended) Add parameter name and value argument to Input Parser scheme
addRequiredAdd required positional argument to input parser scheme
parseParse function inputs

You can define your scheme by calling addRequired, addOptional, and addParameter in any order, but when you call your function that uses the input parser, you should pass in required inputs first, followed by any optional positional inputs, and, finally, any name-value pairs.

Copy Semantics

Handle. To learn how handle classes affect copy operations, see Copying Objects in the MATLAB documentation.

The copy method creates another scheme with the same properties as an existing inputParser object:

pNew = copy(pOld);

Examples

expand all

Input Validation

Check the validity of required and optional function inputs.

Create a custom function with required and optional inputs in the file findArea.m.

function a = findArea(width,varargin)
   p = inputParser;
   defaultHeight = 1;
   defaultUnits = 'inches';
   defaultShape = 'rectangle';
   expectedShapes = {'square','rectangle','parallelogram'};

   addRequired(p,'width',@isnumeric);
   addOptional(p,'height',defaultHeight,@isnumeric);
   addParameter(p,'units',defaultUnits);
   addParameter(p,'shape',defaultShape,...
                 @(x) any(validatestring(x,expectedShapes)));

   parse(p,width,varargin{:});
   a = p.Results.width .* p.Results.height;

The input parser checks whether width and height are numeric, and whether the shape matches a string in cell array expectedShapes. @ indicates a function handle, and the syntax @(x) creates an anonymous function with input x.

Call the function with inputs that do not match the scheme. For example, specify a nonnumeric value for the width input:

findArea('text')
Error using findArea (line 14)
The value of 'width' is invalid. It must satisfy the function: isnumeric.

Specify an unsupported value for shape:

findArea(4,'shape','circle')
Error using findArea (line 14)
The value of 'shape' is invalid. Expected input to match one of these strings:

square, rectangle, parallelogram

The input, ''circle'', did not match any of the valid strings.

Extra Parameter Value Inputs

Store parameter name and value inputs that are not in the input scheme instead of throwing an error.

default = 0;
value = 1;

p = inputParser;
p.KeepUnmatched = true;
addOptional(p,'expectedInputName',default)
parse(p,'extraInput',value);

View the unmatched parameter name and value:

p.Unmatched
ans = 

    extraInput: 1

Case Sensitivity

Enforce case sensitivity when checking function inputs.

p = inputParser;
p.CaseSensitive = true;
defaultValue = 0;
addParameter(p,'InputName',defaultValue)

parse(p,'inputname',10)
'inputname' is not a recognized parameter. For a list of valid name-value pair arguments, see the documentation for this function.

Structure Array Inputs

Parse structure array inputs with the StructExpand property set to true (default) or false.

Expand a structure array input into parameter name and value pairs using the default true value of the StructExpand property.

s.input1 = 10;
s.input2 = 20;
default = 0;

p = inputParser;
addParameter(p,'input1',default)
addParameter(p,'input2',default)
parse(p,s)

p.Results
ans = 

    input1: 10
    input2: 20

Explicitly specifying a parameter name and value pair overrides values in the structure.

parse(p,s,'input2',300)
p.Results
ans = 

    input1: 10
    input2: 300

Accept a structure array input as a single argument by setting the StructExpand property to false.

s2.first = 1;
s2.random = rand(3,4,2);
s2.mytext = 'some text';

p = inputParser;
p.StructExpand = false;
addRequired(p,'structInput')
parse(p,s2)

results = p.Results
fieldList = fieldnames(p.Results.structInput)
results = 

    structInput: [1x1 struct]


fieldList = 

    'first'
    'random'
    'mytext'

Parse Inputs Using validateattributes

Create a function that parses information about people and, if parsing passes, adds the information to a cell array.

Create a function, addPerson, that sets up an inputParser scheme using validateAttributes. The function should accept the list of people, modify the list if necessary and return the list. Use a persistent inputParser to avoid construction of a new object with every function call. If this is the first call to the function, add a titles row to the cell array.

function mlist = addPerson(mlist,varargin)

persistent p
if isempty(p)
    p = inputParser;
    p.FunctionName = 'addPerson';
    addRequired(p,'name',@(x)validateattributes(x,{'char'},...
        {'nonempty'}))
    addRequired(p,'id',@(x)validateattributes(x,{'numeric'},...
        {'nonempty','integer','positive'}))
    addOptional(p,'birthyear',9999,@(x)validateattributes(x,...
        {'numeric'},{'nonempty'}))
    addParameter(p,'nickname','-',@(x)validateattributes(x,...
        {'char'},{'nonempty'}))
    addParameter(p,'favColor','-',@(x)validateattributes(x,...
        {'char'},{'nonempty'}))
end

parse(p,varargin{:})

if isempty(mlist)
    mlist = fieldnames(p.Results)';
end
mlist = [mlist; struct2cell(p.Results)'];

end

Create an empty list, and add a person to it.

pList = {};
pList = addPerson(pList,78,'Joe');
Error using addPerson
The value of 'name' is invalid. Expected input to be one of these types:

char

Instead its type was double.
Error in addPerson (line 17)
parse(p,mlist,name,id,varargin{:}); 

The parsing failed because the function received the inputs in the incorrect order and tried to assign name a value of 78. This entry was not added to pList.

Add several more people to the list.

pList = addPerson(pList,'Joe',78);
pList = addPerson(pList,'Mary',3,1942,'favColor','red');
pList = addPerson(pList,'James',182,1970,'nickname','Jimmy')
pList = 

    'birthyear'    'favColor'    'id'     'name'     'nickname'
    [     9999]    '-'           [ 78]    'Joe'      '-'       
    [     1942]    'red'         [  3]    'Mary'     '-'       
    [     1970]    '-'           [182]    'James'    'Jimmy'   
Was this topic helpful?