Contenido principal

localfunctions

Handles to all local functions in current file

Description

fcns = localfunctions returns a cell array of handles to all local functions in the current MATLAB® file. Within the cell array, localfunctions returns the function handles in an undefined order.

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.

example

Examples

collapse all

In a file named computeEllipseVals.m in your current folder, create a main function that returns a cell array of handles to all the local functions in the file. Each local function calculates a specific metric of an ellipse.

function fcns = computeEllipseVals
fcns = 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 = pi*a*b;
end

Call the computeEllipseVals function to get a cell array of handles to the local functions.

fcns = computeEllipseVals
fcns =

  3×1 cell array

    {       @computeFocus}
    {@computeEccentricity}
    {        @computeArea}

Call a local function using its handle to compute the area of an ellipse that has measurements a = 5 and b = 1. The computeArea function is represented by the third element of the cell array.

fcns{3}(5,1)
ans =

   15.7080

In a file named mystats.m in your current folder, create the mystats script. The script uses a cell array of handles to the local functions in the file to display the mean and median of a vector.

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

fcns = localfunctions;

for i = 1:length(fcns)
    disp(extractAfter(func2str(fcns{i}),2) + ": " + num2str(fcns{i}(x)))
end

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 displays the values calculated by invoking the function handles.

mystats
mean: 4.4167
median: 4.5

Access the cell array of function handles created by the script.

fcns
fcns =

  2×1 cell array

    {  @mymean}
    {@mymedian}

Based on the displayed value, the second element of the cell array is a handle to the mymedian local function. Use this function handle to return the median of an arbitrary vector.

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

    15

Output Arguments

collapse all

Handles to all the local functions in the current file, returned as a cell array of function handles.

Version History

Introduced in R2013b

See Also

Functions