Main Content

inputParser

Input parser for functions

Description

The inputParser object enables you to manage inputs to a function by creating an input parser 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 parser scheme.

After defining your input parser scheme, call the parse function. The inputParser stores information about inputs.

Input Names and ValuesWhere Stored
Matching input parser schemeResults property
Not passed to function and, therefore, assigned default valuesUsingDefaults property
No matching input parser schemeUnmatched property

Creation

Description

example

p = inputParser creates an input parser object with default property values.

Properties

expand all

Indicator to match case when checking argument names, specified as false or true (or 0 or 1). By default, argument name matches are not case sensitive. For example, 'a' matches 'A'. For case-sensitive matches, set CaseSensitive to true (or 1).

This property value is stored as a logical value.

Name of the function to display in error messages, specified as a character vector or string scalar. By default, FunctionName is an empty character vector (''). Typically, you set FunctionName to the name of the function you are validating. Then, if the parse function encounters invalid input arguments, it reports the error using the function name.

This property value is stored as a character vector.

Data Types: char | string

Matching indicator to throw error when an input is not found in the input parser scheme, specified as false or true (or 0 or 1). By default, the parse function throws an error if an input argument name does not match one defined in the input parser scheme. To suppress the error and store the input argument name and value, set KeepUnmatched to true (or 1). The inputParser stores unmatched input argument names and values in the Unmatched property.

This property value is stored as a logical value.

Partial matching indicator for accepting partially matched input names as valid, specified as true or false (or 1 or 0). By default, input parameter names that are leading substrings of parameter names in the input parser scheme are valid and the input value is matched to that parameter. If there are multiple possible matches to the input parameter, MATLAB® throws an error. To require input parameter names to match a name in the input parser scheme exactly, respecting the CaseSensitive property, set PartialMatching to false (or 0).

Partial matching is supported only by arguments that you add to the input parser scheme using the addParameter function.

  • If the value of the StructExpand property is true (or 1), then inputParser does not support partial matching for structure field names that correspond to input parameter names.

  • If PartialMatching and KeepUnmatched are both true (or 1), then MATLAB does not throw an error. Instead, it stores the ambiguous parameter name in the Unmatched property.

This property value is stored as a logical value.

Structure indicator that interprets a structure as a single input or as a set of parameter name-value pairs, specified as true or false (or 1 or 0). By default, the inputParser expands structures into separate inputs, where each field name corresponds to an input parameter name. To consider structures as a single input argument, specify StructExpand as false (or 0).

This property value is stored as a logical value.

This property is read-only.

Argument names defined in the input parser scheme, stored as a cell array of character vectors. Each function that adds an input argument to the scheme updates the Parameters property. These functions include addRequired, addOptional, and addParameter.

Data Types: cell

This property is read-only.

Results specified as the names of valid input arguments and the corresponding values, stored as a structure. A valid input argument is one with a name that matches an argument defined in the input parser scheme. Each field of the Results structure corresponds to the name of an argument in the input parser scheme. The parse function populates the Results property.

Data Types: struct

This property is read-only.

Unmatched input names and values of inputs that do not match input parser scheme, stored as a structure. If the KeepUnmatched property is set to false (or 0), which is the default, or if all inputs match the input parser scheme, then Unmatched is a 1-by-1 structure with no fields. Otherwise, each field of the Unmatched structure corresponds to the name of an input argument that does not match the arguments defined in the input parser scheme.

The parse function populates the Unmatched property.

Data Types: struct

This property is read-only.

Inputs not passed explicitly to the function, stored as a cell array of character vectors. These input arguments are assigned default values in the Results property. The parse function populates the UsingDefaults property.

Data Types: cell

Object Functions

addOptionalAdd optional, positional argument into input parser scheme
addParameterAdd optional name-value pair argument into input parser scheme
addRequiredAdd required, positional argument into input parser scheme
parseParse function inputs
addParamValue(Not recommended) Add optional name-value pair argument into input parser scheme

You can define your input parser scheme by calling the addRequired, addOptional, and addParameter functions in any order. However, when you call the function that uses the input parser, arguments are passed in this order:

  1. Required arguments

  2. Any optional, positional arguments

  3. Any name-value pairs

Examples

collapse all

Check the validity of required and optional arguments.

Create a function in the file findArea.m. The findArea function requires the width input argument and accepts a variable number of additional inputs. The input parser scheme specifies these argument conditions:

  • width (required argument). Since required arguments are positional, width must be the first argument to the findArea function. The input parser checks that width is positive, scalar, and numeric.

  • height (optional argument). Since optional arguments are positional, if height is an argument to the findArea function, then it must be the second argument. The input parser checks that height is positive, scalar, and numeric.

  • 'units' and its associated value (name-value pair). Name-value pairs are optional. When you call the findArea function, specify name-value pairs in any order after positional arguments. The input parser checks that the value for 'units' is a string.

  • 'shape' and its associated value (another name-value pair). The input parser checks that the value for 'shape' is contained in the expectedShapes array.

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

   p = inputParser;
   validScalarPosNum = @(x) isnumeric(x) && isscalar(x) && (x > 0);
   addRequired(p,'width',validScalarPosNum);
   addOptional(p,'height',defaultHeight,validScalarPosNum);
   addParameter(p,'units',defaultUnits,@isstring);
   addParameter(p,'shape',defaultShape,...
                 @(x) any(validatestring(x,expectedShapes)));
   parse(p,width,varargin{:});
   
   a = p.Results.width*p.Results.height; 
end

Call the findArea function several times. The input parser does not throw an error for any of these function calls.

a = findArea(7);
a = findArea(7,3);
a = findArea(13,'shape','square');
a = findArea(13,'units',"miles",'shape','square');

Call the function with arguments that do not match the input parser scheme. Specify a nonnumeric value for the width input:

a = findArea('text')
Error using findArea (line 14)
The value of 'width' is invalid. It must satisfy the function: @(x)isnumeric(x)&&isscalar(x)&&(x>0).

Specify an unsupported value for 'shape'.

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

'square', 'rectangle', 'parallelogram'

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

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 = struct with fields:
    extraInput: 1

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.

Expand a structure argument into name-value pairs.

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

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

p.Results
ans = struct with fields:
    input1: 10
    input2: 20

Accept a structure 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
results = struct with fields:
    structInput: [1x1 struct]

fieldList = fieldnames(p.Results.structInput)
fieldList = 3x1 cell
    {'first' }
    {'random'}
    {'mytext'}

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

Create function addPerson and include an input parser scheme that uses the validateattributes function. The addPerson function accepts a list of people, modifies the list if necessary, and then returns the list. Use a persistent inputParser object to avoid constructing of a new object with every function call.

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 19)
parse(p,varargin{:})

The parsing fails because the function receives arguments in the incorrect order and tries to assign name a value of 78. This entry is 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 =

  4×5 cell array

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

Tips

  • Arguments added to the input parser scheme with the addOptional function are positional. Therefore, add them to the input parser scheme in the same order they are passed into the function.

  • 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.

Extended Capabilities

Version History

Introduced in R2007a