Main Content

Validate Required and Optional Positional Arguments

Positional arguments are arguments with a position and order defined at function declaration. 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.

Set Default Value for Optional Arguments

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)
        x (1,:) double
        y (1,:) double
        maxval (1,1) double = max(max(x),max(y))
        minval (1,1) double = min(min(x),min(y))

    % Function code

You can call this function with any of these syntaxes:


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

    % Function code

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)

    % Function code

Calls to this function must include both arguments.

c = f(2,3)

For more information on calling functions with ignored inputs, see Ignore Inputs in Function Definitions.

See Also


Related Topics