Function Argument Validation
Introduction to Argument Validation
Function argument validation is a way to declare specific restrictions on function arguments. Using argument validation you can constrain the class, size, and other aspects of arguments without writing code in the body of the function to perform these tests.
Function argument validation is declarative, which enables MATLAB® desktop tools to extract information about a function by inspection of specific code blocks. By declaring requirements for arguments, you can eliminate cumbersome argument-checking code and improve the readability, robustness, and maintainability of your code.
The function argument validation syntax simplifies the process of defining optional, repeating, and name-value arguments. The syntax also enables you to define default values in a consistent way.
Where to Use Argument Validation
The use of function argument validation is optional in function definitions. Argument validation is most useful in functions that can be called by any code and where validity of the arguments must be determined before executing the function code. Functions that are designed for use by others can benefit from the appropriate level of restriction on arguments and the opportunity to return specific error messages based on the argument validation checks.
Where Validation Is Not Needed
In local and private functions, and in private or protected methods, the caller is aware of input requirements, so these types of functions can be called with valid arguments.
Where Validation Is Not Allowed
You cannot use argument validation syntax in nested functions, abstract methods, or handle class destructor methods. For more information on argument validation in methods, see Method Syntax.
arguments
Block Syntax
Functions define argument validation in optional code blocks that are delimited by the
keywords arguments
and end
. If used, an
arguments
block must start before the first executable line of the
function.
You can use multiple arguments
blocks in a function, but all blocks
must occur before any code that is not part of an arguments
block.
The highlighted area in the following code shows the syntax for input argument validation.
The function argument declaration can include any of these kinds of restrictions:
Size — The length of each dimension, enclosed in parentheses
Class — The name of a single MATLAB class
Functions — A comma-separated list of validation functions, enclosed in braces
You can also define a default value for the input argument in the function validation declaration for that argument. The default value must satisfy the declared restrictions for that argument.
Size
Validation size is the dimensions of the argument, specified with nonnegative integer
numbers or colons (:
). A colon indicates that any length is allowed in
that dimension. You cannot use expressions for dimensions. The value assigned to the
argument in the function call must be compatible with the specified size, or MATLAB throws an error.
MATLAB indexed assignment rules apply to size specifications. For example, a 1-by-1
value is compatible with the size specified as (5,3)
because
MATLAB applies scalar expansion. Also, MATLAB row-column conversion applies so that a size specified as
(1,:)
can accept a size of 1-by-n and n-by-1.
Here are some examples:
(1,1)
— The input must be exactly 1-by-1.(3,:)
— The first dimension must be 3, and second dimension can be any value.
If you do not specify a size, then any size is allowed unless restricted by validation functions.
Class
Validation class is the name of a single class. The value assigned to the function
input must be of the specified class or convertible to the specified class. Use any
MATLAB class or externally defined class that is supported by MATLAB, except Java, COM classes, and MATLAB class definitions that do not use the classdef
keyword (classes defined before MATLAB software Version 7.6).
Here are some examples:
char
— Input must be of classchar
or a value that MATLAB can convert to achar
, such asstring
.double
— Input can be a numeric value of any precision.cell
— Input must be a cell array.A user-defined class
If you do not specify a class, then any class is allowed unless restricted by validation functions.
Validation Functions
A validation function is a MATLAB function that throws an error if certain requirements are not satisfied by the argument value. Validation functions do not return values and, unlike class and size, cannot change the value of the arguments they are validating.
During the validation process, MATLAB passes the argument value to each validation function listed for that argument. The value passed to the validation functions is the result of any conversion made by the class and size specifications. MATLAB calls each function from left to right and throws the first error encountered.
For a table of predefined validation functions, see Argument Validation Functions.
Default Value
An input argument default value can be any constant or expression that satisfies the size, class, and validation function requirements. Specifying a default value in an argument declaration makes the argument optional. MATLAB uses the default value when the argument is not included in the function call. Default value expressions are evaluated each time the default is used.
Note
Because MATLAB validates the default value only when the function is called without a value for the argument, an invalid default value causes an error only when the function is called without that argument.
Optional arguments must be positioned after required arguments in the function
signature and in the arguments
block. For more information on optional
arguments, see Required and Optional Positional Arguments.
Validation Sequence
Arguments are validated from top to bottom in the arguments
block.
MATLAB validates each part of an argument declaration in a specific order. First
the class is validated, then the size. The result of the class and size validations is
passed to the validation functions. Each step is optional depending on whether class,
size, and validation functions are in the argument declaration.
For more information, see Order of Argument Validation
Conversion to Declared Class and Size
Both class validation and size validation can change the value of an argument. Here are some examples of conversions that MATLAB can perform.
To satisfy class restrictions:
A
char
value can be converted to astring
value.A
single
value can be converted to adouble
.
To satisfy size restrictions:
Scalar expansion can change input size from scalar to nonscalar.
A column vector can be converted to a row vector.
As a result, the validated value in the function body can be different from the value passed when calling the function. For more information on class conversion, see Implicit Class Conversion. To avoid class and size conversions during validation, use argument validation functions instead. For more information, see Avoiding Class and Size Conversions.
Output Argument Validation
Starting in R2022b, argument validation can be used on output arguments. Similar to input arguments, you can validate the class and size of output arguments and also apply validation functions. However, you cannot specify default values for output arguments or refer to previously declared arguments. Output argument validation is always optional. Adding output argument validation helps improve code readability and also maintains consistent output in code that might change over time.
Separate arguments
blocks must be used for validating input and
output arguments. Define the type of arguments block (Input)
or
(Output)
after the arguments
statement. If both
(Input)
and (Output)
argument blocks are used, the
(Output)
block must follow the (Input)
block. then
If no type is specified, then MATLAB assumes the block contains input arguments.
For more information, see arguments
.
Examples of Argument Validation
Basic Argument Validation
This arguments
block specifies the size and class of the three
inputs.
function out = myFunction(A, B, C) arguments A (1,1) string B (1,:) double C (2,2) cell end % Function code ... end
In this function, the variables must meet these validation requirements:
A
is a string scalar.B
is a 1-by-any length vector of doubles.C
is a 2-by-2 cell array.
Value Conversion
The following function illustrates how inputs can be converted to match the classes
specified in the arguments
block. The SpeedEnum
class is an enumeration class created to define the values allowed for the third argument.
function forwardSpeed(a,b,c) arguments a double b char c SpeedEnum end % Function code disp(class(a)) disp(class(b)) disp(class(c)) end
Here is the enumeration class.
classdef SpeedEnum < int32 enumeration Full (100) Half (50) Stop (0) end end
This call to the function uses input values that MATLAB can convert to the declared types. The actual argument types within the function are displayed as output.
forwardSpeed(int8(4),"A string",'full')
double char SpeedEnum
Specific Restrictions Using Validation Functions
Validation functions can restrict arguments in more specific ways. You can use predefined validation functions for many common kinds of validation, and you can define your own validation function to satisfy specific requirements.
For example, this function specifies the following validations using mustBeNumeric
, mustBeReal
, mustBeMember
, and the local function mustBeEqualSize
.
Input
x
must be a real, numeric row vector of any length.Input
v
must be a real, numeric row vector the same size asx
.Input
method
must be a character vector that is one of the three allowed choices. Becausemethod
specifies a default value, this argument is optional.
function myInterp(x,v,method) arguments x (1,:) {mustBeNumeric,mustBeReal} v (1,:) {mustBeNumeric,mustBeReal,mustBeEqualSize(v,x)} method (1,:) char {mustBeMember(method,{'linear','cubic','spline'})} = 'linear' end % Function code .... end % Custom validation function function mustBeEqualSize(a,b) % Test for equal size if ~isequal(size(a),size(b)) eid = 'Size:notEqual'; msg = 'Size of first input must equal size of second input.'; throwAsCaller(MException(eid,msg)) end end
Avoid using function argument validation within custom validation functions. For more information about defining validation functions and a list of predefined validation functions, see Argument Validation Functions.
Output Argument Validation
Starting in R2022b, argument validation can be used on output arguments.
For example, this function validates the size and class of three input arguments and
one output argument using separate arguments blocks. Note that the
(Input)
block must precede the (Output)
block.
function out = myFunction(A, B, C) arguments (Input) A (1,1) string B (1,:) double C (2,2) cell end arguments (Output) out (1,:) double end % Function code ... end
Kinds of Arguments
Function argument validation can declare four kinds of arguments. Functions can define any of these kinds of arguments, but the arguments must be defined in the following order:
Required positional arguments
Optional positional arguments
Repeating positional arguments
Optional name-value arguments
Required and Optional Positional Arguments
Positional arguments must be passed to a function in a specific order. The position of
the value passed in the argument list must correspond to the order that the argument is
declared in the arguments
block. All argument names in the
arguments
block must be unique.
Positional arguments in the arguments
block are required when calling
the function, unless the argument defines a default value. Specifying a default value in the
argument declaration makes a positional argument optional because MATLAB can use the default value when no value is passed in the function call.
The default value can be a constant or an expression that produces a result that
satisfies the argument declaration. The expression can refer to the arguments that are
declared before it in the arguments
block, but not arguments that are
declared after it.
MATLAB evaluates the default value expression only when the argument is not included in the function call.
All optional arguments must be positioned after all required arguments in the
arguments
block. For example, in this argument block,
maxval
and minval
have default values and are
therefore optional.
function myFunction(x,y,maxval,minval) arguments x (1,:) double y (1,:) double maxval (1,1) double = max(max(x),max(y)) minval (1,1) double = min(min(x),min(y)) end % Function code .... end
You can call this function with any of these syntaxes:
myFunction(x,y,maxval,minval) myFunction(x,y,maxval) myFunction(x,y)
An optional positional argument becomes required when its position must be filled in the
function call to identify arguments that come after it. That is, if you want to specify a
value for minval
, you must specify a value for
maxval
.
Ignored Positional Arguments
MATLAB lets you ignore arguments by passing a tilde character
(~
) in place of the argument. You can define a function that ignores
unused positional arguments by adding a tilde character (~
) in the
arguments block corresponding to the position of the argument in the function signature.
Add a tilde character (~
) for each ignored argument in the function
signature.
Ignored arguments cannot have default values or specify class, size, or validation functions.
The tilde character (~
) is treated as an optional argument unless
it is followed by a required positional argument. For example, in this function the tilde
character (~
) represents an optional argument.
function c = f(~) arguments ~ end % Function code end
You can call this function with no arguments.
c = f
Or you can call this function with one argument.
c = f(2)
In the following function, the tilde character (~
) represents a
required argument.
function c = f(~,x) arguments ~ x end % Function code ... end
Calls to this function must include both arguments.
c = f(2,3)
For more information on calling functions with ignored inputs, see Ignore Inputs in Function Definitions.
Repeating Arguments
Repeating arguments are positional arguments that can be specified repeatedly as
arguments. Declare repeating arguments in an arguments
block that
includes the Repeating
attribute.
arguments (Repeating) arg1 arg2 ... end
Functions can have one Repeating
arguments
block for inputs and one for outputs. A
Repeating
input arguments block can contain one or more repeating
arguments, while a Repeating
output arguments block can contain only one
repeating argument.
A function that defines a Repeating
arguments
block can be called with zero or more occurrences of all the
arguments in the block. If a call to a function includes repeating arguments, then all
arguments in the Repeating
arguments
block must be included for each repetition.
For example, if a Repeating
arguments
block defines input arguments x
and
y
, then each repetition must contain both x
and
y
.
Repeating input arguments cannot specify default values and therefore cannot be optional. However, you can call the function without including any repeating arguments.
Functions must declare repeating input arguments after positional arguments and before
name-value arguments. You cannot specify name-value arguments within a
Repeating
block. For information on name-value arguments, see Name-Value Arguments.
In the function, each repeating argument becomes a cell array with the number of elements equal to the number of repeats passed in the function call. The validation is applied to each element of the cell array. If the function is called with zero occurrences of this argument, the cell array has a size of 1-by-0. That is, it is empty.
For example, this function declares a block of three repeating arguments,
x
, y
, and option
.
function [xCell,yCell,optionCell] = fRepeat(x,y,option) arguments (Repeating) x double y double option {mustBeMember(option,["linear","cubic"])} end % Function code % Return cell arrays xCell = x; yCell = y; optionCell = option; end
You can call the function with no inputs or multiples of three inputs. MATLAB creates a cell array for each argument containing all the values passes for
that argument. This call to fRepeat
passes two sets of the three
repeating arguments.
[xCell,yCell,optionCell] = fRepeat(1,2,"linear",3,4,"cubic")
xCell = 1×2 cell array {[1]} {[3]} yCell = 1×2 cell array {[2]} {[4]} optionCell = 1×2 cell array {["linear"]} {["cubic"]}
The following function accepts repeating arguments for x
and
y
inputs in a Repeating
arguments
block. In the body of the function, the values specified as
repeating arguments are available in the cell arrays x
and
y
. This example interleaves the values of x
and
y
to match the required input to the plot
function: plot(x1,y1,…)
.
function myPlotRepeating(x,y) arguments (Repeating) x (1,:) double y (1,:) double end % Function code % Interleave x and y z = reshape([x;y],1,[]); % Call plot function if ~isempty(z) plot(z{:}); end end
Call this function with repeating pairs of arguments.
x1 = 1:10; y1 = sin(x1); x2 = 0:5; y2 = sin(x2); myPlotRepeating(x1,y1,x2,y2)
Avoid Using varargin
for Repeating Arguments
Using varargin
with functions that use argument
validation is not recommended. If varargin
is restricted in size or
class in the repeating arguments block, then the restrictions apply to all values in
varargin
.
If you use varargin
to support legacy code, it must be the only
argument in a Repeating
arguments
block.
For example, this function defines two required positional arguments and
varargin
as the repeating argument.
function f(a, b, varargin) arguments a uint32 b uint32 end arguments (Repeating) varargin end % Function code ... end
Name-Value Arguments
Name-value arguments associate a name with a value that is passed to the function. Name-value arguments:
Can be passed to the function in any order
Are always optional
Must be declared after all positional and repeating arguments
Cannot appear in an
arguments
block that uses theRepeating
attributeMust use unique names even when using multiple name-value structures
Cannot use names that are also used for positional arguments
Declare name-value arguments in an arguments
block using dot notation
to define the fields of a structure. For example, the structure named
NameValueArgs
defines two name-value arguments,
Name1
and Name2
. You can use any valid MATLAB identifier as the structure name.
arguments NameValueArgs.Name1 NameValueArgs.Name2 end
The structure name must appear in the function signature.
function myFunction(NameValueArgs)
Call the function using the field names in the name-value structure.
myFunction(Name1=value1,Name2=value2)
Before R2021a, pass names as strings or character vectors, and separate names and values with commas. Both syntaxes are valid in later releases.
The name of the structure used in the function signature is the name of the structure in the function workspace that contains the names and values passed to the function.
function result = myFunction(NameValueArgs) arguments NameValueArgs.Name1 NameValueArgs.Name2 end % Function code result = NameValueArgs.Name1 * NameValueArgs.Name2; end
r = myFunction(Name1=3,Name2=7)
r = 21
Name-value arguments support partial name matching when there is no ambiguity. For
example, a function that defines LineWidth
and
LineStyle
as its two name-value arguments accepts
LineW
and LineS
, but using Line
results in an error. In general, using full names is the recommended practice to improve
code readability and avoid unexpected behavior.
The same name-value argument can be repeated in a function call without error, but the
last version specified is the one MATLAB honors. For example, this call to plot
specifies the
value for Color
twice. MATLAB displays the plot in red.
plot(x,y,Color="blue",LineStyle="--",Color="red")
Default Values for Name-Value Arguments
You can specify a default value for each name. If you do not specify a default value and the function is called without that name-value argument, then that field is not present in the name-value structure. If no name-value arguments are passed to the function, MATLAB creates the structure, but it has no fields.
To determine what name-value arguments have been passed in the function call, use the
isfield
function.
For example, the following function defines two required positional arguments
(width
and height
) and two name-value arguments
(LineStyle
and LineWidth
). In this example, the
options
structure has two fields (LineStyle
and
LineWidth
) containing either the default values or values specified
as name-value arguments when the function is called.
function myRectangle(width,height,options) arguments width double height double options.LineStyle (1,1) string = "-" options.LineWidth (1,1) {mustBeNumeric} = 1 end % Function code ... end
All of these syntaxes are valid ways to call this function.
myRectangle(4,5) myRectangle(4,5,LineStyle=":",LineWidth=2) myRectangle(4,5,LineWidth=2,LineStyle=":") myRectangle(4,5,LineStyle=":") myRectangle(4,5,LineWidth=2)
Before R2021a, pass names as strings or character vectors, and separate names and values with commas. For example:
myRectangle(4,5,"LineStyle",":","LineWidth",2) myRectangle(4,5,"LineWidth",2,"LineStyle",":")
Using Repeating and Name-Value Arguments
If the function defines repeating arguments, then you must declare the name-value
arguments in a separate arguments
block that follows the repeating
arguments block. For example, this function accepts two repeating arguments,
x
and y
. After specifying all repeats of
x
and y
, you can specify a name-value argument
that assigns the value lin
or log
to the
PlotType
name.
To determine if the function call includes the PlotType
argument,
use the isfield
function to check for the PlotType
field in the scale
structure.
function myLinLog(x,y,scale) arguments(Repeating) x (1,:) double y (1,:) double end arguments scale.PlotType (1,1) string end z = reshape([x;y],1,[]); if isfield(scale,"PlotType") if scale.PlotType == "lin" plot(z{:}) elseif scale.PlotType =="log" loglog(z{:}) end end end
Call this function with or without the name-value argument.
myLinLog(1:5,1:5)
myLinLog(1:5,1:5,1:10,1:100:1000)
myLinLog(1:5,1:5,1:10,1:100:1000,PlotType="log")
Before R2021a, pass names as strings or character vectors, and separate names and values with commas. For example:
myLinLog(1:5,1:5,1:10,1:100:1000,"PlotType","log")
Multiple Name-Value Structures
Function argument blocks can contain multiple name-value structures. However, the
field names must be unique among all structures. This function has two name-value
structures: lineOptions
and fillOptions
. These
structures cannot have the same field names.
The arguments in the myRectangle
function are:
width
andheight
are required positional arguments of typedouble
.lineOptions.LineStyle
is a scalar string with a default value of"-"
.lineOptions.LineWidth
is a scalar numeric with a default value of1
.fillOptions.Color
is a string.fillOptions.Pattern
has no restrictions on its value.
function myRectangle(width,height,lineOptions,fillOptions) arguments width double height double lineOptions.LineStyle (1,1) string = "-" lineOptions.LineWidth (1,1) {mustBeNumeric} = 1 fillOptions.Color string fillOptions.Pattern end % Function Code ... end
Robust Handling of Name-Value Arguments
The best practice for implementing name-value arguments in your functions is by defining
them in an arguments block. An arguments block eliminates the need to write your own code to
parse the name-value arguments, and the block also helps implement robust argument parsing
for both the "name",value
syntax and the name=value
syntax introduced in R2021a.
Enforcing Valid Names
Defining a name-value argument in an arguments block ensures that the name is a valid
identifier. In turn, this helps ensure that your arguments work with both
"name",value
and name=value
syntaxes. For example,
a name-value argument that uses an invalid identifier can work with the comma-separated
syntax:
myFunction(data,"allow-empty",true)
allow-empty=true
throws an error. Defining the
name-value argument in an arguments block ensures that the names you define are valid
MATLAB variable names and compatible with the name=value
syntax.Avoiding Unexpected Results with Text Inputs
Functions that include both optional text inputs and name-value arguments run the risk of MATLAB interpreting text inputs as the names of the name-value arguments. This function includes two optional text inputs and a name-value argument.
function mySignal(tag,unit,opts) arguments tag = "0" unit = "ampere" opts.Magnifier {mustBeMember(opts.Magnifier,["small","medium","big"])} end end
tag
to
"Mag"
and unit
to
"coulomb"
:mySignal("Mag","coulomb")
"Mag"
as the name-value
argument Magnifer
. "coulomb"
is not a valid value
for that name, so the function errors.One way to avoid this is to make tag
a required argument by
removing its default
value:
function mySignal(tag,unit,opts) arguments tag unit = "ampere" opts.Magnifier {mustBeMember(opts.Magnifier,["small","medium","big"])} end end
tag
to "Mag"
and does
not error.Another option is to make all three inputs name-value arguments. This helps users avoid mistakes when specifying inputs because each value is associated with a name, and the order the user specifies the inputs does not affect the end results.
Name-Value Arguments from Class Properties
A useful function syntax in MATLAB uses the public properties of a class for the names of name-value arguments.
To specify name-value arguments for all settable properties defined by a class (that is, all
properties with public SetAccess
), use this syntax in an
arguments
block:
structName.?ClassName
A function can use the "structName
.?
ClassName
" syntax only once. Therefore, a function can define
only one name-value structure that gets its field names from a class, even if using
different classes and structure names.
If the class places restrictions on values that you can assign to the property by using property validation, then the function applies the validation to the individual name-value arguments. For information on property validation, see Validate Property Values.
For example, this function has two required arguments, x
and
y
and accepts any public property name and value for the
matlab.graphics.chart.primitive.Bar
class.
function myBar(x,y,propArgs) arguments x (:,:) double y (:,:) double propArgs.?matlab.graphics.chart.primitive.Bar end propertyCell = namedargs2cell(propArgs); bar(x,y,propertyCell{:}) end
Call the function with the required inputs and any settable property name-value pairs.
x = [1,2,3;4,5,6]; y = x.^2; myBar(x,y) myBar(x,y,FaceColor="magenta",BarLayout="grouped")
Before R2021a, pass names as strings or character vectors, and separate names and values with commas. For example:
myBar(x,y,"FaceColor","magenta","BarLayout","grouped")
Override Specific Properties
You can override the class property validation by redefining the property name with a specific name-value argument in the arguments block.
structName.?ClassName structName.PropertyName (dim1,dim2,...) ClassName {fcn1,fcn2,...}
The specific name-value argument validation overrides the validation defined by class for the individually specified property name.
For example, the following function defines name-value arguments as the properties of
the matlab.graphics.chart.primitive.Bar
class. The function also
overrides the property name FaceColor
to allow only these specific
values: red
or blue
.
The matlab.graphics.chart.primitive.Bar
class has a default value
for FaceColor
that is not one of the restricted values
(red
or blue
). Therefore, the overriding
declaration must assign a default value that satisfies the restriction placed by the
mustBeMember
validation function. That is,
the default value must be red
or blue
.
This function converts the name-value structure to a cell array containing interleaved
names and values using the namedargs2cell
function.
function myBar(x,y,propArgs) arguments x (:,:) double y (:,:) double propArgs.?matlab.graphics.chart.primitive.Bar propArgs.FaceColor {mustBeMember(propArgs.FaceColor,{'red','blue'})} = "blue" end propertyCell = namedargs2cell(propArgs); bar(x,y,propertyCell{:}) end
Call the function using the two required arguments, x
and
y
. Optionally pass any name-value pairs supported by the bar function
and a value for FaceColor
that can be either red
or
blue
. Other values for FaceColor
are not allowed.
x = [1,2,3;4,5,6]; y = x.^2; myBar(x,y) myBar(x,y,FaceColor="red",BarLayout="grouped")
Order of Argument Validation
When a function is called, MATLAB validates the arguments in the order they are declared in the
arguments
block, from top to bottom. Each argument is fully validated
before the next argument is validated. Therefore, any reference to a previously declared
argument uses values that have been validated. Functions throw an error as a result of the
first validation failure.
Validated values can be different from the original values passed as inputs when the
function is called. For example, this function declares the inputs as class uint32
values. The third input declaration assigns a default value equal to
the product of the first two inputs.
function c = f(a, b,c) arguments a uint32 b uint32 c uint32 = a .* b end % Function code ... end
Calling the function with inputs that are a different numeric class (for example,
double
) results in a conversion to uint32
.
c = f(1.8,1.5)
Because the optional argument c
is not specified in the function
call, MATLAB evaluates the default value and assigns it to c
after
converting a
and b
to uint32
values. In this case, the conversion results in a value of 2 for both inputs. Therefore, the
product of a
times b
is four.
c = uint32 4
If you specify a value for the third input, then the function assigns a value to
c
and does not evaluate the default value expression.
c = f(1.8,1.5,25)
c = uint32 25
Avoiding Class and Size Conversions
When an argument value that is passed to a function does not match the class and size required by the validation, MATLAB converts the value to the declared class and size when conversion is possible. To avoid the standard conversions performed by MATLAB from argument validation, use validation functions instead of class and size restrictions. Calls to validation functions do not return values and cannot change the value of the argument.
For example, this function restricts the first input to a two-dimensional array of any
size that is of class double
. The second input must be a 5-by-3 array of any
class.
function f(a,b) arguments a (:,:) double b (5,3) end % Function code end
Because of standard MATLAB type conversion and scalar expansion, you can call this function with the following inputs and not receive a validation error.
f('character vector',144)
By default, MATLAB converts the elements of the character vector to their equivalent numeric
value and applies scalar expansion to create a 5-by-3 array from the scalar value
144
.
Using specialized validation functions can provide more specific argument validation. For example, this function defines specialized validation functions that it uses in place of the class and size specifications for the first and second arguments. These local functions enable you to avoid input value conversions.
mustBeOfClass
restricts the input to a specific class without allowing conversion or subclasses. For a related function, seemustBeA
.mustBeEqualSize
restricts two inputs to be of equal size without allowing scalar expansion. For a related function, seemustBeScalarOrEmpty
.mustBeDims
restricts the input to be of a specified dimension without allowing transposition or scalar expansion. For a related function, seemustBeVector
.
function fCustomValidators(a,b) arguments a {mustBeOfClass(a,'double'), mustBeDims(a,2)} b {mustBeEqualSize(b,a)} end % Function code end % Custom validator functions function mustBeOfClass(input,className) % Test for specific class name cname = class(input); if ~strcmp(cname,className) eid = 'Class:notCorrectClass'; msg = ['Input must be of class ',className,'.']; throwAsCaller(MException(eid,msg)) end end function mustBeEqualSize(a,b) % Test for equal size if ~isequal(size(a),size(b)) eid = 'Size:notEqual'; msg = 'Inputs must have equal size.'; throwAsCaller(MException(eid,msg)) end end function mustBeDims(input,numDims) % Test for number of dimensions if ~isequal(length(size(input)),numDims) eid = 'Size:wrongDimensions'; msg = ['Input must have ',num2str(numDims),' dimension(s).']; throwAsCaller(MException(eid,msg)) end end
Use fCustomValidators
to text the
mustBeOfClass
function. The first argument is not of class
double
, so the function returns an error.
fCustomValidators('character vector',144)
Error using fCustomValidators fCustomValidators('character vector',144) ↑ Invalid argument at position 1. Input must be of class double.
In this call, the number of dimensions of the first input is wrong, so the validation function returns a custom error message.
fCustomValidators(ones(2,2,4),144)
Error using fCustomValidators fCustomValidators(ones(2,2,4),144) ↑ Invalid argument at position 1. Input must have 2 dimension(s).
The mustBeEqualSize
validator function checks to see if the inputs
are of the same size.
fCustomValidators(ones(2,2),144)
Error using fCustomValidators fCustomValidators(ones(2,2),144) ↑ Invalid argument at position 2. Inputs must have equal size.
For related predefined validation functions, see mustBeA
,
mustBeFloat
,
and mustBeVector
.
nargin
in Argument Validation
The nargin
function returns the number of function
input arguments given in the call to the currently executing function. When using function
argument validation, the value returned by nargin
within a function is
the number of positional arguments provided when the function is called.
Repeating arguments are positional arguments and therefore the number of repeating
arguments passed to the function when called is included in the value returned by
nargin
.
The value that nargin
returns does not include optional arguments
that are not included in the function call. Also, nargin
does not count
any name-value arguments.
Use nargin
to determine if optional positional arguments are passed
to the function when called. For example, this function declares three positional arguments
and a name-value argument. Here is how the function determines what arguments are passed
when it is called.
function result = fNargin(a,b,c,namedargs) arguments a (1,1) double b (1,1) double c (1,1) double = 1 namedargs.Format (1,:) char end % Function code switch nargin case 2 result = a + b; case 3 result = a^c + b^c; end if isfield(namedargs,"Format") format(namedargs.Format); end end
In this function call, the value of nargin
is
2
:
result = fNargin(3,4)
result = 7
In this function call, the value of nargin
is
3
:
result = fNargin(3,4,7.62)
result = 4.3021e+04
In this function call, the value of nargin
is 3:
result = fNargin(3,4,7.62,Format="bank")
result = 43020.56
Restrictions on Variable and Function Access
arguments
blocks exist in the function's workspace. Any packages,
classes, or functions added to the scope of the function using the import
command are added to the scope of the arguments
block.
The only variables visible to validator functions and default value expressions are the
input variables already declared. In this function, the default value of
c
is derived from a
and b
.
function c = f(a,b,c) arguments a uint32 b uint32 c uint32 = a * b end % Function code ... end
However, you cannot refer to input variables not yet declared in an
arguments
block. For example, using this declaration for argument
a
in the previous function is not valid because b
and c
have not been declared yet.
arguments a uint32 = b * c b uint32 c uint32 end
Argument validation expressions can reference only previously declared, and therefore validated, arguments. Validation functions and default values for name-value arguments cannot access other name-value arguments.
Limitations on Functions in arguments
Block
Any references to previously declared arguments must be visible in the text of
validation functions and default values. To ensure code transparency, do not use functions
that interact with the function workspace. Specifically, do not use nested functions or
any of the functions listed in the following table in the arguments
block.
assignin | builtin | clear |
dbstack | eval | evalc |
evalin | exist | feval |
input | inputname | load |
nargin | narginchk | nargoutchk |
save | whos | who |
These restrictions apply only within the arguments
block and do not
apply to variables or functions in the body of the function.
Debugging Arguments Blocks
While debugging inside of an arguments block the workspace is read only. This means that it is possible to inspect the workspace and view the values assigned to variables. However, it is not possible to create new variables or change the values assigned to existing variables while the workspace is read only. Once the debugger is outside of the arguments block it will once again be possible to create or edit variables.