MATLAB Input Parsing
When you deploy source code, such as MATLAB analysis routines, anticipate all possible use scenarios to ensure a robust application. Robust code always checks user input to ensure it works properly with your code. MATLAB implements an "inputParser" object that expedites strong checking of required and optional inputs to your custom functions.
-
Implementing Input Parsing
-
To be compatibile with "inputParser," your MATLAB function includes inputs of three different types: required, optional and parameters. Your function declaration must be formatted to include required inputs by name, followed by a single variable to contain optional inputs and parameters. This variable is often called "varargin," or a similar term, standing for "variable arguments in." In MATLAB, "varargin" is a cell array of optional arguments sent to the function.
For example, in "myFunction.m":
[output1, output2] = function myFunction(req_input1, req_input2, varargin)
parser = inputParser;
...
parser.parse(req_input1, req_input2, varargin{:});
%your custom code
end
Checking For Required Inputs
-
Required inputs need to have a specified value while optional inputs can be set to a default value. Add required inputs to your inputParser using the "addRequired()" method of the inputParser class along with checking for valid values. Required and optional inputs must be added in the order they appear in the function call.
For example:
parser.addRequired('req_input1',@ischar); %input 1 must be a string
validInputs = {'apple' 'orange' 'grapes' 'pineapple'};
parser.addRequired('req_input2',@(x)any(strcmp(x,validInputs)));Add optional inputs using the "addOptional()" method. Add default values as an extra argument. For example:
parser.addOptional('opt_input1',35,@isnumeric);
-
Parameters
-
Unlike required and optional inputs, parameters are paired by a parameter name and value in the function call. For example, code to process an image might contain parameters for width and height, included in the function call as:
myImageFunction( ... , 'height', 256, 'width', 128);
The order of parameters does not matter, but they must be added after all required and optional inputs. Parameters are added to the inputParser using the "addParamValue()" method.
parser.addParamValue('ParamName',default_value,validator_code);
Validating Input Values
-
In addition to simple validators such as "@ischar" and "@isnumeric," complex validators verify appropriate ranges of inputs or other attributes.
myValidator = @(x)isnumeric(x) && @(x)isa(x,'double') && (x > 100 || X < -100);
The myValidator variable provides a means to check what type of variable is passed, including numeric, formatted as a double, and either greater than 100 or less than -100.
-
References
- Photo Credit Stockbyte/Stockbyte/Getty Images