Products & Services Solutions Academia Support User Community Company

Learn more about MATLAB   

Validating Inputs with inputParser

MATLAB provides a class called inputParser to handle the different types of arguments passed into an M-file function. Using inputParser, you create a schema that both represents and verifies the content of the entire list of input arguments passed on a call to the function. When used in all of your code development, this schema offers a consistent and thorough means of managing and validating the input information.

This section covers the following topics

To illustrate how to use the inputParser class, the documentation in this section develops a new M-file program called publish_ip, (based on the MATLAB publish function). There are three calling syntaxes for this function:

publish_ip('scriptfile')
publish_ip('scriptfile', 'format')
publish_ip('scriptfile', options)

There is one required argument (scriptfile), one optional argument (format), and a number of optional arguments that are specified as parameter-value pairs (options).

Defining a Specification for Each Input Parameter

Most programs have a block of code toward the beginning that parses the values in the input argument list and checks these values against what is expected. The inputParser class provides the following methods with which you can specify what the inputs are and whether they are required, optional, or to be specified using the parameter-value syntax:

Creating the inputParser Object

Call the class constructor for inputParser to create an instance of the class. This class instance, or object, gives you access to all of the methods and properties of the class.

Begin writing the example publish_ip M-file by entering the following two statements:

function x = publish_ip(scriptfile, varargin)
p = inputParser;   % Create an instance of the class.

After calling the constructor, use the addRequired, addOptional, and addParamValue methods to add arguments to the schema.

Adding Arguments to the Schema

Add any required arguments to the schema using the addRequired method. This method takes two inputs: the name of the required parameter, and an optional handle to a function that validates the parameter:

addRequired(name, validator);

Put an addRequired statement at the end of your publish_ip code. The two arguments for addRequired in this case are a parameter name script to represent the filename input, and a handle to a function that will validate the filename, ischar. After adding the addRequired statement, your publish_ip function should now look like this:

function x = publish_ip(scriptfile, varargin)
p = inputParser;   % Create an instance of the class.

p.addRequired('script', @ischar);

Use the addOptional method to add any arguments that are not required. The syntax for addOptional is similar to that of addRequired except that you also need to specify a default value to be used whenever the optional argument is not passed:

addOptional(name, default, validator);

Add the following statement to your publish_ip M-file. In this case, the validator input is a handle to an anonymous function:

p.addOptional('format', 'html', ...
    @(x)any(strcmpi(x,{'html','ppt','xml','latex'})));

Use addParamValue to specify any arguments that use a parameter-value format. The syntax is

addParamValue(name, default, validator);

Add the following code to your publish_ip M-file:

p.addParamValue('outputDir', pwd, @ischar);
p.addParamValue('maxHeight', [], @(x)x>0 && mod(x,1)==0);
p.addParamValue('maxWidth', [], @(x)x>0 && mod(x,1)==0);

Listing the Parameters

At this point, the schema is complete. Here is the file publish_ip.m:

function x = publish_ip(scriptfile, varargin)
p = inputParser;   % Create an instance of the class.

p.addRequired('script', @ischar);

p.addOptional('format', 'html', ...
    @(x)any(strcmpi(x,{'html','ppt','xml','latex'})));

p.addParamValue('outputDir', pwd, @ischar);
p.addParamValue('maxHeight', [], @(x)x>0 && mod(x,1)==0);
p.addParamValue('maxWidth', [], @(x)x>0 && mod(x,1)==0);

When you call the program, MATLAB stores the name of each argument in the Parameters property of object p. Add the following statement to your publish_ip M-file to display p.Parameters:

disp 'The input parameters for this program are'
disp(p.Parameters)

Save the M-file, and then run it as shown here:

publish_ip('ipscript.m', 'ppt', 'outputDir', ...
    'C:/matlab/test', 'maxWidth', 500, 'maxHeight', 300);

The output is

The input parameters for this program are
   'format'   'maxHeight'   'maxWidth'   'outputDir'   'script'

Parsing Parameter Values on the Function Call

Once you have constructed a schema that represents all possible inputs to the function, the next task is to write the code that parses and verifies these arguments whenever the function is called. The parse method of the inputParser class reads and validates the required scriptfile argument and any optional arguments that follow it in the argument list:

p.parse(scriptfile, varargin{:});

Execution of the parse method validates each argument and also builds a structure from the input arguments. The name of the structure is Results, which is accessible as a property of the object. To get the value of all arguments, type

p.Results

To get the value of any single input argument, type

p.Results.argname

where argname is the name of the argument. Continue with the publish_ip exercise started earlier in this section by removing the two disp statements that were inserted in the last section, and then adding the following lines:

% Parse and validate all input arguments.
p.parse(scriptfile, varargin{:});

% Display the value of a specific argument. 
disp' '
fprintf('\nThe maximum height is %d.\n', ...
     p.Results.maxHeight)

% Display all arguments.
disp ' '
disp 'List of all arguments:'
disp(p.Results)

Now save and execute the M-file, passing the required script file argument, the optional format argument, as well as several parameter-value arguments. MATLAB assigns those values you pass in the argument list to the appropriate fields of the Results structure:

publish_ip('ipscript.m', 'ppt', 'outputDir', ...
    'C:/matlab/test', 'maxWidth', 500, 'maxHeight', 300);

The maximum height is 300.

List of all arguments:
              format: 'ppt'
           maxHeight: 300
            maxWidth: 500
           outputDir: 'C:/matlab/test'
              script: 'ipscript.m'

Packaging Arguments in a Structure

By setting the StructExpand property of the inputParser object to true, you can pass arguments to your function in the form of a structure instead of individually in the argument list. This property must be set prior to calling the parse method.

StructExpand defaults to the true state, so you do not have to make any changes to your test program to run this example.

Put all of the input arguments into a structure:

s.format = 'xml';
s.outputDir = 'C:/matlab/test';
s.maxWidth = 200;
s.maxHeight = 150;

Now call the function, passing the filename and input structure:

publish_ip('ipscript.m', s);

The maximum height is 150.

List of all arguments:
              format: 'xml'
           maxHeight: 150
            maxWidth: 200
           outputDir: 'C:/matlab/test'
              script: 'ipscript.m'

To disable struct expansion, you can include the following statement somewhere in your program code before the p.parse statement:

p.StructExpand = false;

For this example however, leave the StructExpand in its default true state.

Overriding the Input Structure

If you want to pass your argument list in a structure, as described in the previous section, but you also want to alter the value of one or more of these arguments without having to modify the structure, you can do so by passing both the structure and the modified argument:

publish_ip('ipscript.m', s, ...
           'outputDir', 'C:/matlab/R2007a/temp');

List of all arguments:
              format: 'xml'
           maxHeight: 150
            maxWidth: 200
           outputDir: 'C:/matlab/R2007a/temp'
              script: 'ipscript.m'

Arguments That Default

Any arguments that you do not include in a call to your function are given their default values by MATLAB. You defined these default values when you created your schema using the addOptional and addParamValue methods. The UsingDefaults property is a cell array that contains the names of any arguments that were not passed in the function call, and thus were assigned default values.

In your example M-file, remove or comment out the lines that display the maximum height and the list of all arguments, and add the following lines in their place:

% Show which arguments were not specified in the call.
disp' ' 
disp 'List of arguments given default values:' 
for k=1:numel(p.UsingDefaults)
   field = char(p.UsingDefaults(k));
   value = p.Results.(field);
   if isempty(value),   value = '[]';   end
   disp(sprintf('   ''%s''    defaults to %s', field, value))
end

Save the M-file and run it without specifying the format, outputDir, or maxHeight arguments:

publish_ip('ipscript.m', 'maxWidth', 500);

List of arguments given default values:
   'format'    defaults to html
   'outputDir'    defaults to D:\matlabtest
   'maxHeight'    defaults to []

Note that outputDir defaults to your current working directory, as specified near the beginning of your example M-file in the statement

p.addParamValue('outputDir', pwd, @ischar);

Validating the Input Arguments

When you call your function, MATLAB checks any arguments for which you have specified a validator function. If the validator finds an error, MATLAB displays an error message and aborts the function. In the publish function example, the outputDir argument validates the value passed in using @ischar.

Pass a number instead of a string for the outputDir argument:

publish_ip('ipscript.m', 'outputDir', 5);
??? Error using ==> publish_ip at 14
Argument 'outputDir' failed validation ischar.

Handling Unmatched Arguments

MATLAB throws an error if you call your function with any arguments that are not part of the inputParser schema. You can disable this error by setting the KeepUnmatched property to true. When KeepUnmatched is in the true state, MATLAB does not throw an error, but instead stores any arguments that are not in the schema in a cell array of strings accessible through the Unmatched property of the object. KeepUnmatched defaults to false.

In your publish_ip M-file, remove or comment out all of the code that follows the p.addParamValue statements, and add the following code in its place:

p.KeepUnmatched = true;

% Parse and validate all input arguments.
p.parse(scriptfile, varargin{:});

disp ' '
disp 'List of unmatched arguments:'
disp(p.Unmatched)

Save and run the function, passing two arguments that are not defined in the schema:

publish_ip('ipscript.m', s, ...
           'outputDir', 'C:/matlab/R2007a/temp', ...
           'colorSpace', 'CMYK', 'density', 200);

List of unmatched arguments:
    colorSpace: 'CMYK'
       density: 200

Enabling Case-Sensitive Matching

When you pass optional arguments in the function call, MATLAB compares these arguments with the names of parameter-value argument names in the schema. By default, MATLAB does not use case sensitivity in this comparison. So, an argument name entered into the schema (using addParamValue) as maxHeight will match an argument passed as MAXHeight in the function call. You can override the default and make these comparisons case sensitive by setting the CaseSensitive property of the object to true. MATLAB does not error on a case mismatch, however, unless the KeepUnmatched property is set to false: its default state.

At some point in your publish_ip M-file before executing the parse method, set KeepUnmatched to false and CaseSensitive to true. You can also remove the statements that display the list of unmatched arguments. Now execute the publish_ip function using MAXHeight as the name of the argument for specifying maximum height:

p.KeepUnmatched = false;
p.CaseSensitive = true;

% Parse and validate all input arguments.
p.parse(scriptfile, varargin{:});

Save and run the function, using MAXHeight as the name of the argument for specifying maximum height:

publish_ip('ipscript.m', 'ppt', 'outputDir', ...
    'C:/matlab/test', 'maxWidth', 500, 'MAXHeight', 300);
??? Error using ==> publish_ip at 17
Argument 'MaxHeight' did not match any valid parameter of the parser.

Adding the Function Name to Error Messages

Use the FunctionName property to include the name of your function in error messages thrown by the validating function:

At some point in your publish_ip M-file before executing the parse method, set the FunctionName property to PUBLISH_IP, and then run the function:

p.FunctionName = 'PUBLISH_IP';

% Parse and validate all input arguments.
p.parse(scriptfile, varargin{:});

Save and run the function and observe text of the error message:

publish_ip('ipscript.m', 'ppt', 'outputDir', 5, ...
    'maxWidth', 500, 'maxHeight', 300);
??? Error using ==> PUBLISH_IP
Argument 'outputDir' failed validation ischar.

Making a Copy of the Schema

The createCopy method enables you to make a copy of an existing schema. Because the inputParser class uses handle semantics, you cannot make a copy of the object using an assignment statement.

The following statement creates an inputParser object s that is a copy of p:

s = p.createCopy

Summary of inputParser Methods

MethodDescription
addOptionalAdd an optional argument to the schema
addParamValueAdd a parameter-value pair argument to the schema
addRequiredAdd a required argument to the schema
createCopyCreate a copy of the inputParser object
parseParse and validate the named inputs

Summary of inputParser Properties that Control Parsing

PropertyDescription
CaseSensitivityEnable or disable case-sensitive matching of argument names. Defaults to false.
FunctionNameFunction name to be included in error messages. Defaults to an empty string.
KeepUnmatchedEnable or disable errors on unmatched arguments. Defaults to false.
StructExpandEnable or disable passing arguments in a structure. Defaults to true.

Summary of inputParser Properties that Provide Information

PropertyDescription
ParametersNames of arguments defined in inputParser schema.
ResultsNames and values of arguments passed in function call that are in the schema for this function.
UnmatchedNames and values of arguments passed in function call that are not in the schema for this function.
UsingDefaultsNames of arguments not passed in function call that are given default values.

  


Recommended Products

Includes the most popular MATLAB recorded presentations with Q&A sessions led by MATLAB experts.

 © 1984-2009- The MathWorks, Inc.    -   Site Help   -   Patents   -   Trademarks   -   Privacy Policy   -   Preventing Piracy   -   RSS