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. 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” on
page 18-18.
For example, create a function 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
20 Function Basics