Main Content

Pass Function to Another Function

You can use function handles as input arguments to other functions, which are calledfunction functions. These functions evaluate mathematical expressions over a range of values. Typical function functions includeintegral,quad2d,fzero, andfminbnd.

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

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

Similarly, to find the integral of thesinfunction and theexpfunction, pass handles to those functions tointegral.

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 / ( e x - 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 (calledfunction functions) expect that the function associated with the function handle has a certain number of input variables. For example, if you callintegralorfzero, the function associated with the function handle must have exactly one input variable. If you callintegral3, the function associated with the function handle must have three input variables. For information on calling function functions with more variables, seeParameterizing Functions.

Related Examples

More About