localfunctions - Function handles to all local functions in MATLAB file - MATLAB (original) (raw)

Main Content

Function handles to all local functions in MATLAB file

Syntax

Description

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.

example

Examples

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; end

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

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

function ae = computeArea(a,b) ae = piab; end

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

fh =

3×1 cell array

{       @computeFocus}
{@computeEccentricity}
{        @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.

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; end

function m = mymedian(v) n = length(v); 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

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 =

4.4167

med =

4.5000

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]; fh avg2 = fh{2}(x2)

fh =

2×1 cell array

{  @mymean}
{@mymedian}

avg2 =

15

Version History

Introduced in R2013b