This is machine translation

Translated by Microsoft
Mouseover text to see original. Click the button below to return to the English version of the page.

Note: This page has been translated by MathWorks. Click here to see
To view all translated materials including this page, select Country from the country navigator on the bottom of this page.


Function handles to all local functions in MATLAB file


fcns = localfunctions



fcns = localfunctions returns a cell array of function handles, fcns, to all local functions in the current file.

You cannot define local functions in the context of the command line or anonymous functions, so when you call localfunctions from these contexts, you get an empty cell array. Within the cell array, localfunctions returns the function handles in an undefined order.


collapse all

Create the following function in a file, computeEllipseVals.m, in your working folder. The function returns a cell array with handles to all the local functions.

function fh = computeEllipseVals
fh = localfunctions;

function f = computeFocus(a,b)
f = sqrt(a^2-b^2);

function e = computeEccentricity(a,b)
f = computeFocus(a,b);
e = f/a;

function ae = computeArea(a,b)
ae = pi*a*b;

At the command prompt, invoke the function to get a cell array of handles to the local functions.

fh = computeEllipseVals
fh =

  3x1 cell array

    {       @computeFocus}
    {        @computeArea}

Call a local function using its handle to compute the area of an ellipse. The computeArea function handle is the third element in the cell array.

ans =


As of R2016b, you can include local functions in scripts. Therefore, you can use the localfunctions function to create function handles that you can invoke in the script or at the command prompt.

Create the following script in a file, mystats.m, in your working folder. The script creates a cell array with handles to all the local functions.

x = [1 3 5 7 9 10 8 6 4 2 0 -2];

avg = mymean(x)

fh = localfunctions;
med = fh{2}(x) % equivalent to med = mymedian(x,n)

function a = mymean(v)
n = length(v);
a = sum(v)/n;

function m = mymedian(v)
n = length(v);
w = sort(v);
if rem(n,2) == 1
    m = w((n + 1)/2);
    m = (w(n/2) + w(n/2 + 1))/2;

Run the script. MATLAB® computes the average by directly invoking the mymean local function and the median by invoking mymedian local function through a function handle.

avg =


med =


At the command prompt, call the mymean local function using its handle. Variables from the script are accessible at the command prompt. The mymean function handle is the first element in the cell array.

x2 = [1 1 2 6 24 120 720 5040];
avg2 = fh{2}(x2)
fh =

  2x1 cell array

    {  @mymean}

avg2 =


Introduced in R2013b