Input Validation
A function that receives the wrong kind of input should fail early and clearly: "rate must be a number between 0 and 1" is far more useful than an indexing error twenty lines later. Flexible Arguments showed the basic idea with if and error. This lesson covers the tools MATLAB and Octave provide so you don't have to write every check by hand:
| Tool | Best for | Octave 11 |
|---|---|---|
is* tests + error |
A few quick, custom checks | Yes |
narginchk |
Checking the number of inputs | Yes |
validateattributes |
Type, size and value checks in one call | Yes |
validatestring |
Choosing from a list of allowed words | Yes |
mustBe* functions |
One named rule per call | Most of them |
inputParser |
Optional and name-value inputs with defaults | Yes |
arguments block |
Declarative checks for the whole signature | No (MATLAB R2019b+) |
Hand-written checks
The is* family answers yes/no questions about a value. Combine them with error and an identifier of your own:
| Test | True when the value is… |
|---|---|
isnumeric(x) |
any numeric type (double, single, integers) |
ischar(x), iscellstr(x) |
a char array, a cell array of char arrays |
islogical(x) |
true/false values |
isscalar(x), isvector(x), isempty(x) |
1×1, 1×n or n×1, has no elements |
isreal(x), all(isfinite(x(:))) |
not complex, has no Inf/NaN |
isstruct(x), iscell(x), isa(x, 'cls') |
a struct, a cell array, an object of a class |
inputs = {0.15, 1.5, 'abc', [0.1 0.2]};
for k = 1:numel(inputs)
try
fprintf('%.2f\n', monthly_payment(1000, inputs{k}));
catch err
fprintf('%s: %s\n', err.identifier, err.message);
end
end
function p = monthly_payment(amount, rate)
narginchk(2, 2);
if ~isnumeric(rate) || ~isscalar(rate)
error('loan:rateType', 'rate must be a single number.');
end
if rate < 0 || rate >= 1
error('loan:rateRange', 'rate must be in [0, 1), got %g.', rate);
end
p = amount * (1 + rate) / 12;
end95.83
loan:rateRange: rate must be in [0, 1), got 1.5.
loan:rateType: rate must be a single number.
loan:rateType: rate must be a single number.
narginchk(minArgs, maxArgs) raises an error when the function is called with too few or too many inputs.
validateattributes
validateattributes(value, classes, attributes) checks the class and a list of properties in one call. Optional extra arguments name the function, the argument and its position, so the message tells the caller exactly what went wrong:
check_samples([4 8 15 16]);
disp('first call passed')
tests = {[4 8 -15], [1.5 2], {1, 2}, zeros(3)};
for k = 1:numel(tests)
try
check_samples(tests{k});
catch err
disp(err.message)
end
end
function check_samples(n)
validateattributes(n, {'numeric'}, {'vector', 'positive', 'integer'}, ...
'check_samples', 'n', 1);
endfirst call passed
check_samples: n (argument #1) must be positive
check_samples: n (argument #1) must be integer
check_samples: n (argument #1) must be of class:
double int16 int32 int64 int8 single uint16 uint32 uint64 uint8
but was of class cell
check_samples: n (argument #1) must be vector
Commonly used attributes:
| Attribute | Requires |
|---|---|
'scalar', 'vector', 'row', 'column', '2d', 'square' |
A shape |
'size', [r c], 'numel', n, 'nonempty' |
An exact size or count (NaN in size means any) |
'positive', 'nonnegative', 'integer', 'finite', 'nonnan', 'real' |
Element values |
'>', v, '>=', v, '<', v, '<=', v |
A bound |
'increasing', 'nondecreasing' |
An order |
The wording of the messages differs: MATLAB says, for example, Expected input number 1, n, to be positive. while Octave says check_samples: n (argument #1) must be positive. The identifiers differ too (MATLAB:expectedPositive vs Octave:expected-positive), so don't write code that depends on either.
validatestring
validatestring(text, allowed) checks a text option against a list and returns the full matching word. It ignores case and accepts any unambiguous prefix, which makes options pleasant to type:
allowed = {'linear', 'nearest', 'cubic'};
disp(validatestring('LIN', allowed))
disp(validatestring('near', allowed))
try
validatestring('quadratic', allowed);
catch
disp('quadratic is not an allowed method')
endlinear
nearest
quadratic is not an allowed method
mustBe* validators
The mustBe* functions each check one rule and raise an error if it fails; they return nothing when the value is fine. They were designed for arguments blocks and property validation, but you can call them anywhere:
x = 12;
mustBePositive(x);
mustBeInteger(x);
mustBeMember(x, [6 12 24]);
disp('x passed all checks')
checks = {@() mustBeNonnegative([-1 2]), @() mustBeNumeric('7'), ...
@() mustBeLessThanOrEqual(15, 10), @() mustBeNonempty([])};
for k = 1:numel(checks)
try
checks{k}();
catch err
disp(err.message)
end
endx passed all checks
input must be non-negative; found 1 elements that were not: values -1
input must be numeric; found a char
input must be less than or equal to 10.000000; found 1 elements that were not: values 15
input must not be empty
Octave 11 has the classic ones: mustBePositive, mustBeNonnegative, mustBeNonzero, mustBeInteger, mustBeNumeric, mustBeNumericOrLogical, mustBeReal, mustBeFinite, mustBeNonNan, mustBeNonempty, mustBeNonsparse, mustBeMember, mustBeGreaterThan(OrEqual) and mustBeLessThan(OrEqual). Newer MATLAB validators such as mustBeInRange, mustBeText, mustBeTextScalar, mustBeA, mustBeVector, mustBeFile and mustBeNonmissing are MATLAB-only for now; in Octave, use validateattributes or an is* test instead.
inputParser
For functions with optional inputs and name-value options, inputParser handles defaults, validation and error messages for you. You describe the inputs once, then call parse:
make_report([3 1 2]);
make_report([3 1 2], 2, 'Title', 'Sales', 'Sort', true);
try
make_report([3 1 2], 'Colour', 'red');
catch err
disp(err.message)
end
function make_report(data, varargin)
p = inputParser;
p.FunctionName = 'make_report';
addRequired(p, 'data', @(v) isnumeric(v) && isvector(v));
addOptional(p, 'digits', 1, @(v) isnumeric(v) && isscalar(v) && v >= 0);
addParameter(p, 'Title', 'Report', @ischar);
addParameter(p, 'Sort', false, @islogical);
parse(p, data, varargin{:});
opt = p.Results;
values = opt.data;
if opt.Sort
values = sort(values);
end
fmt = sprintf('%%.%df ', opt.digits);
fprintf('%s: %s\n', opt.Title, strtrim(sprintf(fmt, values)));
fprintf(' defaults used: %s\n', strjoin(sort(p.UsingDefaults), ', '));
endReport: 3.0 1.0 2.0
defaults used: Sort, Title, digits
Sales: 1.00 2.00 3.00
defaults used:
make_report: argument 'Colour' is not a declared parameter or switch
| Method / property | Purpose |
|---|---|
addRequired(p, name, validator) |
A positional input that must be present |
addOptional(p, name, default, validator) |
A positional input that may be left out |
addParameter(p, name, default, validator) |
A 'Name', value pair, in any order |
parse(p, args...) |
Checks everything and fills p.Results |
p.Results |
A struct with one field per input |
p.UsingDefaults |
Names of the inputs that were not supplied |
p.KeepUnmatched = true |
Collects unknown names in p.Unmatched instead of erroring |
Validators are just handles that return true/false (or raise an error themselves), so any anonymous function or is* test works.
arguments blocks (MATLAB only)
Modern MATLAB lets you declare each input's size, class, validators and default directly under the function line. MATLAB checks everything before the body runs, and even converts compatible values (an integer becomes a double, for instance):
function a = ring_area(outer, inner, opts)
arguments
outer (1,1) double {mustBePositive}
inner (1,1) double {mustBeNonnegative, mustBeLessThan(inner, outer)} = 0
opts.Units (1,:) char {mustBeMember(opts.Units, {'m', 'cm'})} = 'm'
end
a = pi * (outer^2 - inner^2);
if strcmp(opts.Units, 'cm')
a = a * 1e4;
end
end>> ring_area(2, 1)
ans =
9.4248
>> ring_area(2, 1, Units="cm")
ans =
9.4248e+04
>> ring_area(-2)
Error using ring_area
ring_area(-2)
^^
Invalid argument at position 1. Value must be positive.(MATLAB output. Octave 11 does not support arguments blocks yet.) The Units="cm" call syntax is MATLAB R2021a+; 'Units', 'cm' works too. The portable equivalent is a few explicit checks at the top of the function, which is what the examples above do:
fprintf('%.4f\n', ring_area(2, 1));
fprintf('%.4g\n', ring_area(2, 1, 'Units', 'cm'));
try
ring_area(-2);
catch err
disp(err.message)
end
function a = ring_area(outer, inner, varargin)
if nargin < 2
inner = 0;
end
validateattributes(outer, {'numeric'}, {'scalar', 'positive'}, 'ring_area', 'outer', 1);
validateattributes(inner, {'numeric'}, {'scalar', 'nonnegative', '<', outer}, 'ring_area', 'inner', 2);
p = inputParser;
addParameter(p, 'Units', 'm', @(u) any(strcmp(u, {'m', 'cm'})));
parse(p, varargin{:});
a = pi * (outer^2 - inner^2);
if strcmp(p.Results.Units, 'cm')
a = a * 1e4;
end
end9.4248
9.425e+04
ring_area: outer (argument #1) must be positive
Classes can validate their properties with the same syntax (Width (1,1) double {mustBePositive} = 1); see Classes (classdef).
Guidelines
- Validate at the boundary: public functions that users call. Internal helpers that only receive already-checked data don't need to repeat the checks.
- Give your errors identifiers (
'loan:rateRange') so callers can catch specific problems (see Error Handling). - Say what was expected and what was received:
rate must be in [0, 1), got 1.5. - Don't over-restrict. If a function works for any numeric type, accept
{'numeric'}rather than only'double'.
Learn more: Flexible Arguments for varargin and nargin, Unit Testing to check that invalid inputs really raise errors.
Test yourself
What does validatestring('NEA', {'linear', 'nearest'}) return?
'NEA''nearest'true- An error
In an inputParser, which method adds a 'Name', value option?
addRequiredaddOptionaladdParameteraddSwitch
What does mustBePositive(5) return?
true1- Nothing; it only raises an error when the check fails
- The value 5