MATLAB Programming Fundamentals - MathWorks

(やまだぃちぅ) #1

Pass Function to Another Function


You can use function handles as input arguments to other functions, which are called
function functions. These functions evaluate mathematical expressions over a range of
values. Typical function functions include integral, quad2d, fzero, and fminbnd.

For example, to find the integral of the natural log from 0 through 5, pass a handle to the
log function to integral.

a = 0;
b = 5;
q1 = integral(@log,a,b)

q1 = 3.0472

Similarly, to find the integral of the sin function and the exp function, pass handles to
those functions to integral.

q2 = integral(@sin,a,b)

q2 = 0.7163

q3 = integral(@exp,a,b)

q3 = 147.4132

Also, you can pass a handle to an anonymous function to function functions. An
anonymous function is a one-line expression-based MATLAB® function that does not
require a program file. For example, evaluate the integral of x/(ex−1) on the range
[0,Inf]:

fun = @(x)x./(exp(x)-1);
q4 = integral(fun,0,Inf)

q4 = 1.6449

Functions that take a function as an input (called function functions) expect that the
function associated with the function handle has a certain number of input variables. For
example, if you call integral or fzero, the function associated with the function handle
must have exactly one input variable. If you call integral3, the function associated with
the function handle must have three input variables. For information on calling function
functions with more variables, see “Parameterizing Functions”.

13 Function Handles

Free download pdf