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.

Call Local Functions Using Function Handles

This example shows how to create handles to local functions. If a function returns handles to local functions, you can call the local functions outside of the main function. This approach allows you to have multiple, callable functions in a single file.

Create the following function in a file, ellipseVals.m, in your working folder. The function returns a struct with handles to the local functions.

% Copyright 2015 The MathWorks, Inc.

function fh = ellipseVals
fh.focus = @computeFocus;
fh.eccentricity = @computeEccentricity;
fh.area = @computeArea;

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;

Invoke the function to get a struct of handles to the local functions.

h = ellipseVals
h = 

  struct with fields:

           focus: @computeFocus
    eccentricity: @computeEccentricity
            area: @computeArea

Call a local function using its handle to compute the area of an ellipse.

ans =


Alternatively, you can use the localfunctions function to create a cell array of function handles from all local functions automatically. This approach is convenient if you expect to add, remove, or modify names of the local functions.

See Also

Related Examples

More About

Was this topic helpful?