Ways to Parse Function Inputs

MATLAB® is dynamically typed, which means that variables do not have a declared type and can hold different types of values. However, values always belong to a specific type, and a program can always query the class and size of a variable’s current value.

Function input arguments are variables in the function workspace whose values come from the calling code or command-line users. When a function is widely used by others, it should determine if the input values match the values expected by the code in the function.

Argument checking allows the function to provide more useful information when input values are unexpected and the function is unable to perform as intended. MATLAB provides several ways to simplify the process of checking and processing function inputs.

Function Argument Validation

Many functions in MATLAB use one of these patterns for input arguments:

  • One or more required input arguments

  • One or more required input arguments followed by one or more optional input arguments

  • One of the previous patterns followed by name-value pairs

An effective way to implement these common patterns is to declare the arguments using a function arguments block, as described in Function Argument Validation. This syntax is new for release R2019b and does not work in earlier releases.

Function argument validation is a way to declare specific restrictions on function input arguments. It enables you to constrain the class, size, and other aspects of function input values without writing code in the body of the function to perform these tests.

validateattributes

The validateattributes function enables you to verify that the inputs to a function conform to a set of requirements. Call validateattributes for each input argument with parameters specifying argument requirements.

inputParser

For complex function signatures, use an inputParser object to express input argument requirements programmatically. An inputParser object parses and validates a set of inputs.

See Also

| |

Related Topics