Accept a variable number of inputs or outputs, check for valid values
Most functions do not require argument declarations or validation because MATLABĀ® is an untyped language. However, if your function has wide usage and you need to verify the type, size, or other aspects of inputs to ensure that your code works as expected, you can define an arguments block.
function z = mySharedFunction(x,y,NameValueArgs)
arguments
x (1,1) double % scalar
y double {mustBeVector,mustBePositive}
NameValueArgs.A string
NameValueArgs.B string = "default"
end
...
end
Argument Validation Functions Validate specific requirements of arguments using validation functions. Write your own functions to check for specific argument requirements.
Check Function Inputs with validateattributes This example shows how to verify that the inputs to your function conform to a set of requirements using the validateattributes function.
Parse Function Inputs Define required and optional inputs, assign defaults to optional inputs, and validate all inputs to a custom function using the Input Parser.
Support Variable Number of Inputs Define a function that accepts a variable number of input arguments using varargin. The varargin argument is a cell array that contains the function inputs, where each input is in its own cell.
Support Variable Number of Outputs Define a function that returns a variable number of output arguments using varargout. Output varargout is a cell array that contains the function outputs, where each output is in its own cell.
Ignore Inputs in Function Definitions If your function accepts a predefined set of inputs, but does not use all the inputs, use the tilde (~) operator to ignore them in your function definition.