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));
Parse Function Inputs