This topic explains the term local function, and shows how to create and use local functions.
MATLAB® program files can contain code for more than one function. In a function file, the first function in the file is called the main function. This function is visible to functions in other files, or you can call it from the command line. Additional functions within the file are called local functions, and they can occur in any order after the main function. Local functions are only visible to other functions in the same file. They are equivalent to subroutines in other programming languages, and are sometimes called subfunctions.
As of R2016b, you can also create local functions in a script file, as long as they all appear after the last line of script code. For more information, see Add Functions to Scripts.
For example, create a function file named
mystats.m that contains a main function,
mystats, and two local functions,
function [avg, med] = mystats(x) n = length(x); avg = mymean(x,n); med = mymedian(x,n); end function a = mymean(v,n) % MYMEAN Example of a local function. a = sum(v)/n; end function m = mymedian(v,n) % MYMEDIAN Another example of a local function. w = sort(v); if rem(n,2) == 1 m = w((n + 1)/2); else m = (w(n/2) + w(n/2 + 1))/2; end end
The local functions
mymedian calculate the average and median of the input list. The main function
mystats determines the length of the list
n and passes it to the local functions.
Although you cannot call a local function from the command line or from functions in other files, you can access its help using the
help function. Specify names of both the file and the local function, separating them with a
mymean Example of a local function.
Local functions in the current file have precedence over functions in other files. That is, when you call a function within a program file, MATLAB checks whether the function is a local function before looking for other main functions. Therefore, you can create an alternate version of a particular function while retaining the original in another file.
All functions, including local functions, have their own workspaces that are separate from the base workspace. Local functions cannot access variables used by other functions unless you pass them as arguments. In contrast, nested functions (functions completely contained within another function) can access variables used by the functions that contain them.