MATLAB Programming Fundamentals - MathWorks

(やまだぃちぅ) #1

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

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

h = ellipseVals

h =

struct with fields:

focus: @computeFocus
eccentricity: @computeEccentricity

13 Function Handles

Free download pdf