parse - Parse function inputs - MATLAB (original) (raw)

Syntax

Description

parse([p](#d126e896744),[argList](#d126e896766)) parses and validates the inputs in arglist.

example

Examples

collapse all

Create an input parser scheme that checks that a required input is a nonnegative, numeric scalar. The syntax @(x) creates a handle to an anonymous function with one input.

p = inputParser; argName = 'num'; validationFcn = @(x) (x > 0) && isnumeric(x) && isscalar(x); addRequired(p,argName,validationFcn)

Parse an invalid input, such as -1:

The value of 'num' is invalid. It must satisfy the function: @(x)(x>0)&&isnumeric(x)&&isscalar(x).

Parse and validate required and optional function inputs.

Create a function in the file findArea.m. ThefindArea function requires the width input argument and accepts a variable number of additional inputs. The input parser scheme specifies these argument conditions:

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:

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.

Input Arguments

collapse all

Input parser scheme, specified as an inputParser object.

Inputs to parse and validate, specified as a comma-separated list. The elements of argList can be any data type. The input parser determines argument validity using the validation function you specified when you added arguments to the input parser scheme.

Example: 'textA',13,mtxB

Example: varargin{:}

Extended Capabilities

Version History

Introduced in R2007a