Declare function argument validation
collapse all in page
Syntax
argumentsargName1 (dimensions) class {validators} = defaultValue
...argNameN ...
endarguments (Repeating)argName1 (dimensions) class {validators}
...argNameN ...
endarguments (Output)argName1 (dimensions) class {validators}
...argNameN ...
endarguments (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 with Input
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
— Input size, specified as a comma-separated list of two or more numbers, such as(dimensions)
(1,2)
,(3,5,2)
, or(1,:)
. A colon allows any length in that dimension.
cannot include expressions.(dimensions)
The dimensions of the input must match
exactly or be compatible with the size specified by(dimensions)
. For example,(dimensions)
(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 Compatible Array Sizes for Basic Operations for more information.
— Class or MATLAB data type specified by name, such asclass
double
. 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.
— Comma-separated list of validation functions, such as{validators}
mustBeNumeric
andmustBeScalarOrEmpty
, enclosed in curly brackets. Validation functions error when the input arguments do not match their conditions. Unlike
, validation functions do not modify input arguments. For a list of validation functions, see Argument Validation Functions.class
— 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 thedefaultValue
arguments
block.
For name-value arguments,
uses the form arg
, where nv.name
is a structure name in the function signature and nv
is the argument name in the arguments block. For instance, define a function that accepts name-value arguments using a structure named name
options
.
y = myFunction(x,options)
In the arguments block, specify the names for name-value arguments as fields:
arguments x options.Name1 options.Name2end
For more information on using arguments
blocks in general, see arguments Block Syntax.
example
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 as myplot(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.
example
Output Argument Blocks
arguments (Output) ... end
declares output arguments for a function. The output arguments block is optional. If you include one or more output arguments
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.
example
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)
example
Examples
collapse all
Restrict Size and Type of Input
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)
m = 3s = 1.6330
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)
m = 3s = 1.6330
If you call the function with a vector that contains nonnumeric values, the mustBeNumeric
validation function throws an error.
a = ["1" "3" "5"];[m,s] = twoStats(a)
Error using twoStatsInvalid argument at position 1. Value must be numeric.
Define Name-Value Arguments
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 the arguments
block.
Declare the myRectangle
function with options
as a structure name. The two fields of options
, LineStyle
and LineWidth
, 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.
Define Repeating Input Arguments
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
, and style
. Restrict the input arguments x
and y
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{:}); endend
Call fRepeat
with two groups of inputs. MATLAB creates a cell array containing all the values passed in for x
, 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 to plot
.
x1 = 1:10;y1 = 1:10; s1 = ":"; x2 = 1:7;y2 = 1:1.5:10;s2 = "--";fRepeat(x1,y1,s1,x2,y2,s2)
Restrict Output Values with Argument Validation
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.7674y1 = 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
Repeating Outputs with Argument Validation
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}; endend
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)
sum1 = 4 6sum2 = 1 1
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.
x1 + y2
ans = 1 2 2 3
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
collapse all
Supported Data Types
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 the classdef
keyword).
Tips
Using data type restrictions can result in implicit conversions of input arguments. For example:
For this function, if you pass the stringfunction y = myFunction(inputArg1) arguments inputArg1 (1,1) double end ...
"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
.
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
C/C++ Code Generation
Generate C and C++ code using MATLAB® Coder™.
Code generation supports most features of arguments
blocks, including size and class validation, validation functions, and default values. Code generation also supports the namedargs2cell function.
Code generation does not support these features of arguments
blocks:
Size validation, class validation, and validation functions for repeating arguments
Multiple repeating input arguments
Name-value input arguments at entry-point functions
Size validation for table and timetable objects.
For additional code generation considerations, see Generate Code for arguments Block That Validates Input and Output Arguments (MATLAB Coder). If you use an arguments
block to specify entry-point input types, some additional limitations apply. See Use Function Argument Validation to Specify Entry-Point Input Types (MATLAB Coder).
Version History
Introduced in R2019b
expand all
R2024b: Code generation supports using class properties to define name-value arguments
You can generate code for non-entry-point MATLAB functions that use the structName.?ClassName
syntax. See Validate Name-Value Arguments.
R2023b: Use argument validation to specify entry-point input types in MATLAB code for code generation
You can specify input types using arguments
blocks in a MATLAB entry-point function. If one or more of the inputs are instances of MATLAB classes that you authored, you can also specify the types of the class properties using property validation in the class definition. See Generate Code for arguments Block That Validates Input and Output Arguments (MATLAB Coder).
R2023a: Code generation supports validation of name-value arguments
You can generate code for arguments
blocks that validate name-value arguments in your MATLAB code. Name-value argument validation is not supported in entry-point functions. See Generate Code for arguments Block That Validates Input and Output Arguments (MATLAB Coder).
R2023a: Code generation supports output argument validation
You can generate code for arguments
blocks that perform output argument validation in your MATLAB code.
R2023a: Use any name for repeating input arguments in MATLAB code for code generation
You can use any valid MATLAB identifier for the name of a repeating input argument inside an arguments
block.
R2022b: Code generation supports function argument validation
You can generate code for arguments
blocks that perform input argument validation in your MATLAB function. Code generation does not support repeating arguments other than varargin
, name-value arguments, and output argument validation.
R2022b: Argument validation for output arguments
The new arguments (Output)
and arguments (Output,Repeating)
blocks enable you to apply argument validation to output arguments of functions and class methods.
See Also
function
Topics
- Function Argument Validation
- Validate Name-Value Arguments
MATLAB Command
You clicked a link that corresponds to this MATLAB command:
Run the command by entering it in the MATLAB Command Window. Web browsers do not support MATLAB commands.
Select a Web Site
Choose a web site to get translated content where available and see local events and offers. Based on your location, we recommend that you select: .
You can also select a web site from the following list:
Americas
- América Latina (Español)
- Canada (English)
- United States (English)
Europe
- Belgium (English)
- Denmark (English)
- Deutschland (Deutsch)
- España (Español)
- Finland (English)
- France (Français)
- Ireland (English)
- Italia (Italiano)
- Luxembourg (English)
- Netherlands (English)
- Norway (English)
- Österreich (Deutsch)
- Portugal (English)
- Sweden (English)
- Switzerland
- Deutsch
- English
- Français
- United Kingdom (English)
Contact your local office