arguments

Declare function argument validation

Syntax

arguments
    argName1 (dimensions) dataType {validators} = defaultValue
    ...
    argNameN ...
end

arguments (Repeating)
    ... 
end

Description

example

arguments ... end declares input arguments for a function. The arguments block is optional. If you include an arguments block, it must appear before the first executable line of the function. Functions can include multiple arguments blocks.

Each argument can have one or more restrictions or a default value, as shown in this syntax:

argName (dimensions) dataType {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 Compatible Array Sizes for Basic Operations for more information.

  • dataType — Data type, specified as a class name, such as double. The input must be the specified type or a type that can be converted to that type. For example, a function that specifies double accepts values of type single and converts them to double.

  • {validators} — Comma-separated list of validation functions, such as mustBeNumeric and mustBeScalar, enclosed in curly brackets. Validation functions error when the input arguments do not match their conditions. Unlike dataType, 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 the arguments 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, see arguments Block Syntax.

arguments (Repeating) ... end declares repeating 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 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 repeating arguments, see Repeating Arguments.

Examples

collapse all

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 =

     3


s =

    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 =

     3


s =

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

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{:});
    end
end

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)

Plot showing two lines

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:

    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 value 123 of type double.

    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, or mustBeNumeric.

    • To avoid conversion of numeric values to strings, use mustBeText, mustBeTextScalar, or mustBeNonZeroLengthText.

    • To avoid size conversions, use mustBeVector or mustBeScalarOrEmpty.

Introduced in R2019b