Function Argument Validation

Introduction to Argument Validation

Function argument validation is a way to declare specific restrictions on function input arguments. Using argument validation you can constrain the class, size, and other aspects of function input values 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 input 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 inputs 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 argument inputs and the opportunity to return specific error messages based on the inputs to the functions.

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 Argument Validation in Class Methods.

arguments Block Syntax

Functions define argument validation in 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 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 input 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 class char, or a value that MATLAB can convert to a char, such as string.

  • double — Input can be a numeric value of any precision.

  • cell — Input must be a cell array.

  • A user-defined class, such as an enumeration class, can restrict inputs to more specific values and enables you to control what conversions are supported.

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 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 input argument because of standard MATLAB conversion rules. Therefore, the validated value in the function body can be different from the value passed when calling the function. The conversion rules are derived from the rules that MATLAB applies for indexed assignment of the form:

A(indices) = value

MATLAB can determine that the left side value has requirements for class and size and, in certain cases, can convert the right side value to be of the required class and size.

For related information, see Avoiding Class and Size Conversions.

Examples of 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 input 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 input 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 as x.

  • Input method must be a character vector that is one of the three allowed choices. Because method 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.

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:

  1. Required positional arguments

  2. Optional positional arguments

  3. Repeating positional arguments

  4. 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 input 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 input 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 Function Inputs.

Repeating Arguments

Repeating arguments are positional arguments that can be specified repeatedly as input arguments. Declare repeating arguments in an arguments block that includes the Repeating attribute.

arguments (Repeating)
    arg1
    arg2
    ...
end

Functions can have only one Repeating arguments block, which can contain one or more repeating arguments.

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 arguments x and y, then each repetition must contain both x and y.

Repeating 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 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 input 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 the Repeating attribute

  • Must 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, passed as a string or character vector.

myFunction('Name1',value1,'Name2',value2)

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

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 the following 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)

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 pair 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 linLog(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")

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 and height are required positional arguments of type double.

  • lineOptions.LineStyle is a scalar string with a default value of "-".

  • lineOptions.LineWidth is a scalar numeric with a default value of 1.

  • 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

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')

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')

Argument Validation in Class Methods

Validating method input arguments is useful in public methods because calls to the method might not originate in class code. You can use function argument validation in concrete class methods, including concrete methods defined in abstract classes. However, abstract methods (methods not implemented by the class) cannot define arguments blocks. For information on class methods, see Methods and Abstract Classes and Class Members.

If a classdef file includes method prototypes for methods defined in separate files, include the arguments blocks in the separate files defining the method. For more information on defining methods in separate files, see Methods in Separate Files.

Subclass methods do not inherit function argument validation. In subclass methods that override superclass methods, you can add the same argument validation to the subclass method as is used in the superclass method.

Handle class destructor methods cannot use argument validation. A method named delete in a handle subclass that includes an arguments block is not treated as a destructor. (In other words, it is not called by MATLAB when the object is destroyed). For more information on class destructor methods, see Handle Class Destructor.

Order of Argument Validation

When a function is called, MATLAB validates the input 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 input 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

During the validation process, MATLAB applies class and then size validation before calling any validation functions. If a default value is used for an optional input that is omitted in the function call, this value is assigned to the argument before applying any steps in the validation process.

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. However, conversion might not be the desired behavior.

Here are some examples of conversions that MATLAB can perform.

To satisfy numeric class restriction:

  • A char value can be converted to its Unicode® numeric value.

  • A string can be converted to a number or NaN if the string is not a representation of a single number.

To satisfy size restriction:

  • Scalar expansion can change size from scalar to nonscalar.

  • A column vector can be converted to a row vector.

To eliminate the standard conversions performed by MATLAB from input 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 input 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 input 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, see mustBeA.

  • mustBeEqualSize restricts two inputs to be of equal size without allowing scalar expansion. For a related function, see mustBeScalarOrEmpty.

  • mustBeDims restricts the input to be of a specified dimension without allowing transposing or scalar expansion. For a related function, see mustBeVector.

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 ', cname];
        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 dimensions: ',num2str(numDims)];
        throwAsCaller(MException(eid,msg))
    end
end

The mustBeOfClass function enforces strict class matching by requiring a match with the name of the class. A more general approach could use the isa function to also match subclasses of the specified class.

The mustBeEqualSize and mustBeDims functions enforce the strict declarations for the input arguments.

fCustomValidators('character vector',144)
Invalid input 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)
Invalid input argument at position 1. Input must have 2 dimensions

The mustBeEqualSize validator function restricts the second input to a specific dimension, which is provided in the error message.

fCustomValidators(ones(2,2),144)
Invalid input argument at position 2. Input must be of size [5  3]

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.

  • nargin determines if the optional positional argument c is passed to the function with a switch block.

  • isfield determines if the name-value argument for Format is passed to the function.

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.

assigninbuiltinclear
dbstackevalevalc
evalinexistfeval
inputinputnameload
narginnarginchknargoutchk
savewhoswho

These restrictions apply only within the arguments block and do not apply to variables or functions in the body of the function.

See Also

|

Related Topics