arguments

Declare function argument validation

Description

example

arguments ... end delimits a code block used at the beginning of a function to declare input argument restrictions. Inside an arguments block, you can impose restrictions on the sizes and classes of input arguments, and can test for specific values using validation functions.

arguments (Repeating) ... end delimits a block of repeating arguments.

Examples

collapse all

Use an arguments block to restrict the size and class of the input argument.

Write a function that restricts the size and class of the input argument to a matrix of numeric values. For more information on using arguments blocks, see arguments Block Syntax.

function [m,s] = Stat(x)
    arguments
        x (:,:) {mustBeNumeric}
    end
    m = mean(x,'all');
    s = std(x,1,'all');
end

Call the function on an input of the wrong size. An error results.

[m,s] = Stat(rand(10,10,10))
Invalid input argument at position 1. Value must be a matrix.

Define repeating arguments.

Repeating arguments are single 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. x and y must be vectors of doubles or convertible to doubles. style must be the character string '--' or ':' .

For more information on repeating arguments, see Repeating Arguments.

function fRepeat(x,y,style)
    arguments (Repeating)
        x (1,:) double
        y (1,:) double
        style {mustBeMember(style,{'--',':'})}       
    end
    
    % Interleave 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.

x1 = 1:10; x2 = 1:5;
y1 = 1:10; y2 = 1:5;
s1 = ':'; s2 = '--';
fRepeat(x1,y1,s1,x2,y2,s2)

Introduced in R2019b