addRequired

Class: inputParser

Add required positional argument to input parser scheme

Syntax

addRequired(p,argName)
addRequired(p,argName,validationFcn)

Description

addRequired(p,argName) adds required argument, argName, to the input parser scheme of inputParser object, p.

addRequired(p,argName,validationFcn) includes a validation function for the input argument.

Input Arguments

p

Object of class inputParser.

argName

String that specifies the internal name for the input argument.

Arguments added with addRequired are positional. When you call a function with positional inputs, you must specify inputs in the order that they are added to the input parser scheme.

validationFcn

Handle to a function that checks if the input argument is valid.

inputParser accepts two types of validation functions: functions that return true or false, and functions that pass or throw an error. Both types of validation functions must accept a single input argument.

Examples

expand all

Add Required Input

Create an inputParser object and add a required input named myinput to the input scheme.

p = inputParser;
argName = 'myinput';
addRequired(p,argName);

Validate Required Input

Check whether a required input named num is a numeric scalar greater than zero.

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

The syntax @(x) creates a handle to an anonymous function with one input.

Attempt to parse an invalid input, such as -1:

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

Validate Required Input with validateattributes

Create an inputParser object and define a validation function using validateattributes to test that required input is numeric, positive, and even. Add the required input to the scheme.

p = inputParser;
argName = 'evenPosNum';
validationFcn = @(x) validateattributes(x,{'numeric'},...
    {'even','positive'}); 
addRequired(p,argName,validationFcn)

Parse an input string. Parse will fail.

parse(p,'hello')
The value of 'evenPosNum' is invalid. Expected input to be one of these types:

double, single, uint8, uint16, uint32, uint64, int8, int16, int32, int64

Instead its type was char.

Parse an odd number. Parse will fail.

 parse(p,13)
The value of 'evenPosNum' is invalid. Expected input to be even.

Parse an even, positive number. Parse will pass.

parse(p,42)
Was this topic helpful?