Main Content

Parse Function Inputs

This example shows how to define required and optional inputs, assign defaults to optional inputs, and validate all inputs to a custom function using the Input Parser.

The Input Parser provides a consistent way to validate and assign defaults to inputs, improving the robustness and maintainability of your code. To validate the inputs, you can take advantage of existing MATLAB® functions or write your own validation routines.

Step 1. Define your function.

Create a function in a file named printPhoto.m. The printPhoto function has one required input for the file name, and optional inputs for the finish (glossy or matte), color space (RGB or CMYK), width, and height.

function printPhoto(filename,varargin)

In your function declaration statement, specify required inputs first. Use varargin to support optional inputs.

Step 2. Create an inputParser object.

Within your function, call inputParser to create a parser object.

p = inputParser;

Step 3. Add inputs to the scheme.

Add inputs to the parsing scheme in your function using addRequired, addOptional, or addParameter. For optional inputs, specify default values.

For each input, you can specify a handle to a validation function that checks the input and returns a scalar logical (true or false) or errors. The validation function can be an existing MATLAB function (such as ischar or isnumeric) or a function that you create (such as an anonymous function or a local function).

In the printPhoto function, filename is a required input. Define finish and color as optional inputs, and width and height as optional parameter value pairs.

defaultFinish = 'glossy';
validFinishes = {'glossy','matte'};
checkFinish = @(x) any(validatestring(x,validFinishes));

defaultColor = 'RGB';
validColors = {'RGB','CMYK'};
checkColor = @(x) any(validatestring(x,validColors));

defaultWidth = 6;
defaultHeight = 4;

addRequired(p,'filename',@ischar);
addOptional(p,'finish',defaultFinish,checkFinish)
addOptional(p,'color',defaultColor,checkColor)
addParameter(p,'width',defaultWidth,@isnumeric)
addParameter(p,'height',defaultHeight,@isnumeric)

Inputs that you add with addRequired or addOptional are positional arguments. When you call a function with positional inputs, specify those values in the order they are added to the parsing scheme.

Inputs added with addParameter are not positional, so you can pass values for height before or after values for width. However, parameter value inputs require that you pass the input name (height or width) along with the value of the input.

If your function accepts optional input strings or character vectors and name-value arguments, specify validation functions for the optional inputs. Otherwise, the Input Parser interprets the optional strings or character vectors as parameter names. For example, the checkFinish validation function ensures that printPhoto interprets 'glossy' as a value for finish and not as an invalid parameter name.

Step 4. Set properties to adjust parsing (optional).

By default, the Input Parser makes assumptions about case sensitivity, function names, structure array inputs, and whether to allow additional parameter names and values that are not in the scheme. Properties allow you to explicitly define the behavior. Set properties using dot notation, similar to assigning values to a structure array.

Allow printPhoto to accept additional parameter value inputs that do not match the input scheme by setting the KeepUnmatched property of the Input Parser.

p.KeepUnmatched = true;

If KeepUnmatched is false (default), the Input Parser issues an error when inputs do not match the scheme.

Step 5. Parse the inputs.

Within your function, call the parse method. Pass the values of all of the function inputs.

parse(p,filename,varargin{:})

Step 6. Use the inputs in your function.

Access parsed inputs using these properties of the inputParser object:

  • Results — Structure array with names and values of all inputs in the scheme.

  • Unmatched — Structure array with parameter names and values that are passed to the function, but are not in the scheme (when KeepUnmatched is true).

  • UsingDefaults — Cell array with names of optional inputs that are assigned their default values because they are not passed to the function.

Within the printPhoto function, display the values for some of the inputs:

disp(['File name: ',p.Results.filename])
disp(['Finish: ', p.Results.finish])

if ~isempty(fieldnames(p.Unmatched))
   disp('Extra inputs:')
   disp(p.Unmatched)
end
if ~isempty(p.UsingDefaults)
   disp('Using defaults: ')
   disp(p.UsingDefaults)
end

Step 7. Call your function.

The Input Parser expects to receive inputs as follows:

  • Required inputs first, in the order they are added to the parsing scheme with addRequired.

  • Optional positional inputs in the order they are added to the scheme with addOptional.

  • Positional inputs before parameter name and value pair inputs.

  • Parameter names and values in the form Name1,Value1,...,NameN,ValueN.

Pass several combinations of inputs to printPhoto, some valid and some invalid:

printPhoto('myfile.jpg')
File name: myfile.jpg
Finish: glossy
Using defaults: 
    'finish'    'color'    'width'    'height'
printPhoto(100)
Error using printPhoto (line 23)
The value of 'filename' is invalid. It must satisfy the function: ischar.
printPhoto('myfile.jpg','satin')
Error using printPhoto (line 23)
The value of 'finish' is invalid. Expected input to match one of these strings:

'glossy', 'matte'

The input, 'satin', did not match any of the valid strings. 
printPhoto('myfile.jpg',height=10,width=8)
File name: myfile.jpg
Finish: glossy
Using defaults: 
    'finish'    'color'

When using name-value arguments before R2021a, pass names as strings or character vectors, and separate names and values with commas. For example:

printPhoto('myfile.jpg','height',10,'width',8)

To pass a value for the nth positional input, either specify values for the previous (n – 1) inputs or pass the input as a parameter name and value pair. For example, these function calls assign the same values to finish (default 'glossy') and color:

printPhoto('myfile.gif','glossy','CMYK')  % positional

printPhoto('myfile.gif',color='CMYK')   % name and value

See Also

|

Related Topics