Documentation

Local Functions

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. The first function in the file (the main 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. 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.

Local functions can occur in any order, as long as the main function appears first. Each function begins with its own function definition line.

For example, create a program file named `mystats.m` that contains a main function, `mystats`, and two local functions, `mymean` and `mymedian`.

```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 `mymean` and `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 main function and the local function, separating them with a `>` character:

`help mystats>mymean`
` 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. This allows you to 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.