Documentation Center

  • Trial Software
  • Product Updates

parse

Class: inputParser

Parse function inputs

Syntax

parse(p,argList)

Description

parse(p,argList) parses and validates the inputs in arglist.

Input Arguments

p

Object of class inputParser.

argList

Comma separated list of inputs to parse and validate for your custom function. The class of each input depends upon your function definition.

Examples

expand all

Input Parsing

Parse and validate required and optional function inputs.

Create a custom function with required and optional inputs in the file findArea.m.

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

   addRequired(p,'width',@isnumeric);
   addOptional(p,'height',defaultHeight,@isnumeric);
   addParameter(p,'units',defaultUnits);
   addParameter(p,'shape',defaultShape,...
                 @(x) any(validatestring(x,expectedShapes)));

   parse(p,width,varargin{:});
   a = p.Results.width .* p.Results.height;

The input parser checks whether width and height are numeric, and whether the shape matches a string in cell array expectedShapes. @ indicates a function handle, and the syntax @(x) creates an anonymous function with input x.

Call the function with inputs that do not match the scheme. For example, specify a nonnumeric value for the width input:

findArea('text')
Error using findArea (line 14)
The value of 'width' is invalid. It must satisfy the function: isnumeric.

Specify an unsupported value for shape:

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

square, rectangle, parallelogram

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

See Also

| | |

Was this topic helpful?