11.9.3 Parsing Arguments

If none of the preceding validation functions is sufficient there is also the class inputParser which can perform extremely complex input checking for functions.

: p = inputParser ()

Create object p of the inputParser class.

This class is designed to allow easy parsing of function arguments. The class supports four types of arguments:

  1. mandatory (see addRequired);
  2. optional (see addOptional);
  3. named (see addParameter);
  4. switch (see addSwitch).

After defining the function API with these methods, the supplied arguments can be parsed with the parse method and the parsing results accessed with the Results accessor.

: inputParser.Parameters

Return list of parameter names already defined.

: inputParser.Results

Return structure with argument names as fieldnames and corresponding values.

: inputParser.Unmatched

Return structure similar to Results, but for unmatched parameters. See the KeepUnmatched property.

: inputParser.UsingDefaults

Return cell array with the names of arguments that are using default values.

: inputParser.CaseSensitive = boolean

Set whether matching of argument names should be case sensitive. Defaults to false.

: inputParser.FunctionName = name

Set function name to be used in error messages; Defaults to empty string.

: inputParser.KeepUnmatched = boolean

Set whether an error should be given for non-defined arguments. Defaults to false. If set to true, the extra arguments can be accessed through Unmatched after the parse method. Note that since Switch and Parameter arguments can be mixed, it is not possible to know the unmatched type. If argument is found unmatched it is assumed to be of the Parameter type and it is expected to be followed by a value.

: inputParser.StructExpand = boolean

Set whether a structure can be passed to the function instead of parameter/value pairs. Defaults to true.

The following example shows how to use this class:

function check (varargin)
  p = inputParser ();                      # create object
  p.FunctionName = "check";                # set function name
  p.addRequired ("pack", @ischar);         # mandatory argument
  p.addOptional ("path", pwd(), @ischar);  # optional argument

  ## create a function handle to anonymous functions for validators
  val_mat = @(x) isvector (x) && all (x <= 1) && all (x >= 0);
  p.addOptional ("mat", [0 0], val_mat);

  ## create two arguments of type "Parameter"
  val_type = @(x) any (strcmp (x, {"linear", "quadratic"}));
  p.addParameter ("type", "linear", val_type);
  val_verb = @(x) any (strcmp (x, {"low", "medium", "high"}));
  p.addParameter ("tolerance", "low", val_verb);

  ## create a switch type of argument
  p.addSwitch ("verbose");

  p.parse (varargin{:});  # Run created parser on inputs

  ## the rest of the function can access inputs by using p.Results.
  ## for example, get the tolerance input with p.Results.tolerance
endfunction
check ("mech");           # valid, use defaults for other arguments
check ();                 # error, one argument is mandatory
check (1);                # error, since ! ischar
check ("mech", "~/dev");  # valid, use defaults for other arguments

check ("mech", "~/dev", [0 1 0 0], "type", "linear");  # valid

## following is also valid.  Note how the Switch argument type can
## be mixed into or before the Parameter argument type (but it
## must still appear after any Optional argument).
check ("mech", "~/dev", [0 1 0 0], "verbose", "tolerance", "high");

## following returns an error since not all optional arguments,
## 'path' and 'mat', were given before the named argument 'type'.
check ("mech", "~/dev", "type", "linear");

Note 1: A function can have any mixture of the four API types but they must appear in a specific order. Required arguments must be first and can be followed by any Optional arguments. Only the Parameter and Switch arguments may be mixed together and they must appear at the end.

Note 2: If both Optional and Parameter arguments are mixed in a function API then once a string Optional argument fails to validate it will be considered the end of the Optional arguments. The remaining arguments will be compared against any Parameter or Switch arguments.

See also: nargin, validateattributes, validatestring, varargin.

© 1996–2020 John W. Eaton
Permission is granted to make and distribute verbatim copies of this manual provided the copyright notice and this permission notice are preserved on all copies.
Permission is granted to copy and distribute modified versions of this manual under the conditions for verbatim copying, provided that the entire resulting derived work is distributed under the terms of a permission notice identical to this one.
Permission is granted to copy and distribute translations of this manual into another language, under the above conditions for modified versions.
https://octave.org/doc/v6.3.0/Parsing-Arguments.html