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 Values | Where Stored |
---|---|
Matching input parser scheme | Results property |
Not passed to function and, therefore, assigned default values | UsingDefaults property |
No matching input parser scheme | Unmatched property |
Creation
Syntax
Description
creates an input parser object with default property values.p
= inputParser
Properties
CaseSensitive
— Indicator to match case
false
(default) | true
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.
FunctionName
— Name of function for error message
empty character vector, ''
. (default) | character vector | string scalar
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
KeepUnmatched
— Matching indicator
false
(default) | true
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.
PartialMatching
— Partial matching indicator
true
(default) | false
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 istrue
(or 1), theninputParser
does not support partial matching for structure field names that correspond to input parameter names.If
PartialMatching
andKeepUnmatched
are bothtrue
(or 1), then MATLAB does not throw an error. Instead, it stores the ambiguous parameter name in theUnmatched
property.
This property value is stored as a logical value.
StructExpand
— Structure indicator
true
(default) | false
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.
Parameters
— Argument names
cell array of character vectors
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
Results
— Results
structure
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
Unmatched
— Unmatched input
structure
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
UsingDefaults
— Inputs not passed explicitly to function
cell array of character vectors
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
addOptional | Add optional, positional argument into input parser scheme |
addParameter | Add optional name-value pair argument into input parser scheme |
addRequired | Add required, positional argument into input parser scheme |
parse | Parse 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:
Required arguments
Any optional, positional arguments
Any name-value pairs
Examples
Input Validation
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 thefindArea
function. The input parser checks thatwidth
is positive, scalar, and numeric.height
(optional argument). Since optional arguments are positional, ifheight
is an argument to thefindArea
function, then it must be the second argument. The input parser checks thatheight
is positive, scalar, and numeric.'units'
and its associated value (name-value pair). Name-value pairs are optional. When you call thefindArea
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 theexpectedShapes
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.
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 = struct with fields:
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
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'}
Parse Inputs Using validateattributes
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 theaddParameter
function.
Extended Capabilities
Thread-Based Environment
Run code in the background using MATLAB® backgroundPool
or accelerate code with Parallel Computing Toolbox™ ThreadPool
.
This function fully supports thread-based environments. For more information, see Run MATLAB Functions in Thread-Based Environment.
Version History
Introduced in R2007a
MATLAB Command
You clicked a link that corresponds to this MATLAB command:
Run the command by entering it in the MATLAB Command Window. Web browsers do not support MATLAB commands.
Select a Web Site
Choose a web site to get translated content where available and see local events and offers. Based on your location, we recommend that you select: .
You can also select a web site from the following list
How to Get Best Site Performance
Select the China site (in Chinese or English) for best site performance. Other MathWorks country sites are not optimized for visits from your location.
Americas
- América Latina (Español)
- Canada (English)
- United States (English)
Europe
- Belgium (English)
- Denmark (English)
- Deutschland (Deutsch)
- España (Español)
- Finland (English)
- France (Français)
- Ireland (English)
- Italia (Italiano)
- Luxembourg (English)
- Netherlands (English)
- Norway (English)
- Österreich (Deutsch)
- Portugal (English)
- Sweden (English)
- Switzerland
- United Kingdom (English)
Asia Pacific
- Australia (English)
- India (English)
- New Zealand (English)
- 中国
- 日本Japanese (日本語)
- 한국Korean (한국어)