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
You can add local functions in any order, as long as they all appear after the rest of the
script code. Each function begins with its own function definition statement, and ends
with the end keyword. The definition statement is the first executable line of any function,
for example, function a = mymean(v,n). For more information about function
definition statements, including how to create them, see “Create Functions in Files” on
page 20-2.
Access Help
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 command. Specify the names of both
the script and the local function, separating them with a > character:
help mystats>mymean
mymean Example of a local function.
Run Code
To run a script, including all local functions, click the Run (for scripts) or Run All
(for live scripts) button, or type the saved script name in the Command Window. You can
also run individual sections in a script by clicking the Run Section button.
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 functions. This allows you to create an alternate
version of a particular function while retaining the original in another file.
Scripts create and access variables in the base workspace. Local functions, similar to
other functions, have their own workspaces that are separate from the base workspace.
Add Functions to Scripts