arguments - Declare function argument validation - MATLAB (original) (raw)
Declare function argument validation
Syntax
arguments
argName1 (dimensions) class {validators} = defaultValue
...
argNameN ...
end
arguments (Repeating)
argName1 (dimensions) class {validators}
...
argNameN ...
end
arguments (Output)
argName1 (dimensions) class {validators}
...
argNameN ...
end
arguments (Output,Repeating)
argName (dimensions) class {validators}
end
Description
Input Argument Blocks
arguments ... end
declares input arguments for a function. The arguments block is optional. If you include one or more arguments
blocks, they must appear before the first executable line of the function. MATLAB® treats any argument block that is not labeled explicitly withInput
or Output
as an input block.
Each argument can have one or more restrictions or a default value, as shown in this syntax:
_`argName (dimensions) class {validators} = defaultValue`_
_`(dimensions)`_
— Input size, specified as a comma-separated list of two or more numbers, such as(1,2)
,(3,5,2)
, or(1,:)
. A colon allows any length in that dimension._`(dimensions)`_
cannot include expressions.
The dimensions of the input must match_`(dimensions)`_
exactly or be_compatible_ with the size specified by_`(dimensions)`_
. For example,(1,:)
specifies the input must be a 1-by-n row vector, but an _n_-by-1 column vector is compatible. The function reshapes a row vector input into a column vector. Similarly, a size of(2,3)
allows scalar input, but it expands the input to a 2-by-3 matrix. See Validate Size and Class for more information._`class`_
— Class or MATLAB data type specified by name, such asdouble
. The input must be the specified type or a type that can be converted to that type. For example, a function that specifiesdouble
accepts values of classsingle
and converts them todouble
. For more information on conversions, see Implicit Class Conversion._`{validators}`_
— Comma-separated list of validation functions, such asmustBeNumeric
andmustBeScalarOrEmpty
, enclosed in curly brackets. Validation functions error when the input arguments do not match their conditions. Unlike_`class`_
, validation functions do not modify input arguments. For a list of validation functions, see Argument Validation Functions._`defaultValue`_
— Default values must conform to the specified size, type, and validation rules. A default value can also be an expression. Specifying a default value makes the argument optional. Optional arguments must be positioned after required arguments in the function signature and in thearguments
block.
For name-value arguments, _`arg`_
uses the form _`nv.name`_
, where_`nv`_
is a structure name in the function signature and _`name`_
is the argument name in the arguments block. For instance, define a function that accepts name-value arguments using a structure named options
.
y = myFunction(x,options)
In the arguments block, specify the names for name-value arguments as fields:
arguments x options.Name1 options.Name2 end
For more information on using arguments
blocks in general, seearguments Block Syntax.
arguments (Repeating) ... end
declares repeating input arguments.
For example, if you create a function named myplot
with repeating arguments X
, Y
, and style
, the function accepts multiple sets of these three arguments, such asmyplot(x1,y1,style1,x2,y2,style2)
. MATLAB creates a cell array that contains all the values passed in for that argument.
Functions can include only one repeating input arguments block. If the function includes both repeating and name-value arguments, declare name-value arguments in their own, separate arguments block after the repeating arguments block.
For more information on using validation with repeating arguments, see Validate Repeating Arguments.
Output Argument Blocks
arguments (Output) ... end
declares output arguments for a function. The output arguments block is optional. If you include one or more outputarguments
blocks, they must appear after all input blocks but before the first executable line of the function. When including both input and output blocks in a function, including the (Input)
and (Output)
attributes explicitly is recommended for readability. See Repeating Outputs with Argument Validation for an example.(since R2022b)
Like input arguments, output arguments can have one or more restrictions, as shown in this syntax:
_`argName (dimensions) class {validators}`_
See the description for arguments ... end
for additional details. Unlike input arguments, output arguments cannot define a default value, and validation functions applied to an output argument cannot reference an earlier output argument.
arguments (Output,Repeating) ... end
declares a repeating output argument for a function. You can use argument validation for a repeating output argument, but you can define only one repeating output argument per function.varargout
can appear in a repeating output arguments block as long as it is the only output argument. (since R2022b)
Examples
Write a function that restricts the size of the input argument to a row vector of any length. Use a validation function to restrict the elements of that vector to numeric values.
function [m,s] = twoStats(x) arguments x (1,:) {mustBeNumeric} end m = mean(x,"all"); s = std(x,1,"all"); end
Call the function on a three-element row vector.
a = [1 3 5]; [m,s] = twoStats(a)
Calling the function with a column vector is also valid because row and column vectors are compatible.
a = [1 3 5]'; [m,s] = twoStats(a)
If you call the function with a vector that contains nonnumeric values, themustBeNumeric
validation function throws an error.
a = ["1" "3" "5"]; [m,s] = twoStats(a)
Error using twoStats Invalid argument at position 1. Value must be numeric.
To declare optional name-value arguments for a function, include a structure name in the function declaration, and define the argument names as fields of that structure in thearguments
block.
Declare the myRectangle
function withoptions
as a structure name. The two fields ofoptions
, LineStyle
andLineWidth
, are the names in the function’s name-value arguments:
function myRectangle(X,Y,options) arguments X double Y double options.LineStyle (1,1) string = "-" options.LineWidth (1,1) {mustBeNumeric} = 1 end % Function code ... end
Both of the argument names have defined default values, so they are both optional. All of these syntaxes are valid ways to call the 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. Both syntaxes are valid in later releases.
Repeating arguments are single arguments or groups of arguments that can be repeated zero or more times in a function call. The fRepeat
function accepts repeating groups of arguments x
, y
, andstyle
. Restrict the input arguments x
andy
to vectors of double values or values convertible to doubles. Restrict style
to the strings "--"
and":"
.
function fRepeat(x,y,style)
arguments (Repeating)
x (1,:) double
y (1,:) double
style {mustBeMember(style,["--",":"])}
end
% Reshape the cell arrays of inputs and call plot function
z = reshape([x;y;style],1,[]);
if ~isempty(z)
plot(z{:});
end
end
Call fRepeat
with two groups of inputs. MATLAB creates a cell array containing all the values passed in forx
, another array for the values of y
, and a third for the values of style
. The function then reshapes those arrays into a 1-by-6 cell array, z
, and passes it toplot
.
x1 = 1:10; y1 = 1:10; s1 = ":"; x2 = 1:7; y2 = 1:1.5:10; s2 = "--"; fRepeat(x1,y1,s1,x2,y2,s2)
Write a function that rotates a two-dimensional square patch about point (0.4, 0.4) by a user-specified number of degrees. Return _x_- and_y_-coordinates of the final image as output arguments, and restrict those values to be positive. In other words, the function should return coordinates only when the final result of the rotation is entirely in the first quadrant.
function [xfinal,yfinal] = rotatePatch(angle) arguments (Output) xfinal {mustBePositive} yfinal {mustBePositive} end x = [0.1 0.1 0.7 0.7]; y = [0.1 0.7 0.7 0.1]; p = patch(x,y,"red"); rotate(p,[0 0 1],angle,[0.4 0.4 0]) xfinal = p.Vertices(:,1); yfinal = p.Vertices(:,2); end
Call the function with an angle of 15 degrees. This rotation does not move any of the vertices out of the first quadrant, so the function returns without error.
[x1,y1] = rotatePatch(15)
x1 =
0.1879
0.0326
0.6121
0.7674
y1 =
0.0326
0.6121
0.7674
0.1879
Call the function with an angle of 35 degrees, which moves the lower-left vertex out of the first quadrant. The negative _x_-coordinate does not satisfy the output argument validation, so the function returns an error.
[x2,y2] = rotatePatch(35)
Invalid output 'xfinal'. Value must be positive.
Error in rotatePatch (line 12) end
Write a function that accepts repeating pairs of vectors and returns the sum of each pair. Restrict the inputs and outputs to row vectors.
function vectorSum = repeatSum(a,b) arguments (Input,Repeating) a (1,:) b (1,:) end arguments (Output,Repeating) vectorSum (1,:) end
n = numel(a); vectorSum{n} = a{n} + b{n}; for i = 1:n-1 vectorSum{i} = a{i} + b{i}; end end
Calculating the final output and assigning it to vectorSum{n}
before the for
-loop preallocates space for the cell array. Expanding the cell array in the loop without preallocation can have a negative effect on performance.
Define two pairs of vectors. Call repeatSum
on with the two pairs as input. The input arguments block validation converts column vectors to row vectors because they are compatible sizes.
x1 = [1 2]; y1 = [3 4]; x2 = [1; 0]; y2 = [0; 1]; [sum1,sum2] = repeatSum(x1,y1,x2,y2)
Because the inputs are restricted to row vectors, the sum of each pair of vectors is always a row vector. However, the output validation helps ensure that the function produces row vectors even if the function is revised at a later date. For example, if the input validation were changed to the mustBeVector
function, pairs could be composed of one row vector and one column vector without conversion. In that case, the sum of x1
and y2
is a matrix.
The output of the revised repeatSum
would error because the matrix would not pass the output validation.
Limitations
- Argument blocks are not supported in nested functions, abstract methods, or handle class destructor methods.
More About
Argument declarations can specify any MATLAB class or externally defined class that is supported by MATLAB, except Java classes, COM classes, and MATLAB classes defined before MATLAB software Version 7.6 (in other words, class definitions that do not use theclassdef
keyword).
Tips
- Using data type restrictions can result in implicit conversions of input arguments. For example:
function y = myFunction(inputArg1)
arguments
inputArg1 (1,1) double
end
...
For this function, if you pass the string"123"
as the input argument, MATLAB converts the string to the numeric value123
of typedouble
.
Validation functions do not change input values in any way, so to avoid data type conversion, use one or more validator functions instead of a data type to restrict the input. For example:- To avoid conversion of strings to numeric values, use
mustBeA
,mustBeFloat
, ormustBeNumeric
. - To avoid conversion of numeric values to strings, use
mustBeText
,mustBeTextScalar
, ormustBeNonZeroLengthText
. - To avoid size conversions, use
mustBeVector
ormustBeScalarOrEmpty
.
- To avoid conversion of strings to numeric values, use
- MATLAB is able to provide code completions and suggestions for functions with
arguments
blocks based on the information contained in the arguments block. This information is available without requiring afunctionSignatures.json
file. For more information on customizing code suggestions and completions see, Customize Code Suggestions and Completions.
Extended Capabilities
Version History
Introduced in R2019b
You can generate code for arguments
blocks that perform output argument validation in your MATLAB code.
You can use any valid MATLAB identifier for the name of a repeating input argument inside anarguments
block.
You can generate code for arguments
blocks that perform input argument validation in your MATLAB function. Code generation does not support repeating arguments other thanvarargin
, name-value arguments, and output argument validation.
The new arguments (Output)
and arguments (Output,Repeating)
blocks enable you to apply argument validation to output arguments of functions and class methods.