Types of Functions
In this section...
“Local and Nested Functions in a File” on page 20-20
“Private Functions in a Subfolder” on page 20-21
“Anonymous Functions Without a File” on page 20-21
Local and Nested Functions in a File
Program files can contain multiple functions. Local and nested functions are useful for
dividing programs into smaller tasks, making it easier to read and maintain your code.
Local functions are subroutines that are available within the same file. Local functions are
the most common way to break up programmatic tasks. In a function file, which contains
only function definitions, local functions can appear in the file in any order after the main
function in the file. In a script file, which contains commands and function definitions,
local function must be at the end of the file. (Functions in scripts are supported in R2016b
or later.)
For example, create a function file named myfunction.m that contains a main function,
myfunction, and two local functions, squareMe and doubleMe:
function b = myfunction(a)
b = squareMe(a)+doubleMe(a);
end
function y = squareMe(x)
y = x.^2;
end
function y = doubleMe(x)
y = x.*2;
end
You can call the main function from the command line or another program file, although
the local functions are only available to myfunction:
myfunction(pi)
ans =
16.1528
20 Function Basics