||Declare function name, inputs, and outputs|
This example shows how to create a function in a program file.
Help text appears in the Command Window when you use
help function. Create help text for your program
by inserting comments at the beginning.
This example shows how to run a function that requires some initial setup, such as input argument values, while working in the Editor.
There are several types of functions available with MATLAB®, including local functions, nested functions, private functions, and anonymous functions.
An anonymous function is a function that is not stored
in a program file. It is associated with a variable whose data type
function_handle. Anonymous functions can accept
inputs and return outputs, just as standard functions do, but can
contain only a single executable statement.
Local functions are functions that follow the main function in the file in a file. They are only visible to other functions in the same file and are equivalent to subroutines in other programming languages.
A nested function is a function that is completely contained within a parent function. Any function in a program file can include a nested function.
To limit the scope of a function, designate it as
private by storing it in a subfolder with the name
The private function is available only to functions in the folder
immediately above the
private subfolder, or to
scripts called by the functions that reside in the parent folder.
To determine which function to call when multiple functions in the current scope have the same name, MATLAB uses function precedence order.
Variables used within nested and anonymous functions must be present in the text of the code. If you add a variable to the workspace of an anonymous function, a nested function, or a function that contains a nested function dynamically, MATLAB issues an error.