function
Declare function name, inputs, and outputs
Description
function [y1,...,yN] = myfun(x1,...,xM)
declares a function named myfun
that accepts inputs x1,...,xM
and returns outputs y1,...,yN
. This declaration statement must be the first executable line of the function. Valid function names begin with an alphabetic character, and can contain letters, numbers, or underscores.
With one output, brackets are optional:
function y = myfun(x1,...,xM)
With no outputs, omit the equal sign:
function myfun(x1,...,xM)
With no inputs, parentheses are optional:
function [y1,...,yN] = myfun
You can save your function:
In a function file which contains only function definitions. The name of the file must match the name of the first function in the file.
In a script file which contains commands and function definitions. Script files cannot have the same name as a function in the file.
Before R2024a: Local functions in scripts must be defined at the end of the file, after the last line of script code.
Files can include multiple local functions or nested functions. For readability, use the end
keyword to indicate the end of each function in a file. The end
keyword is required when:
Any function in the file contains a nested function.
The function is a local function within a function file, and any local function in the file uses the
end
keyword.The function is a local function within a script file.