10. More on Functions

Society for Industrial and Applied Mathematics eBooks · 2005

10.1. Function Handles Many problems tackled with MATLAB require one function to be passed as an argument to another. The usual mechanism for doing this is through a function handle. A function handle is a MATLAB data type that contains all the information necessary to evaluate a function. It can be created by putting the @ character before a function name. We illustrate using ezplot, which plots a function ƒ(x) over a default range of [− 2π, 2π]. If fun is a function M-file of the form required by ezplot then we can write ezplot (@fun) As well as being an M-file, fun can be the name of a built-in function: ezplot (@sin) Function handles were introduced in MATLAB 6 and they supersede an earlier syntax in which a function name was passed in a string, as in ezplot ( ‘exp’). A function that accepts another function as an argument will need to evaluate the passed function. Evaluation is achieved simply by treating the function handle as if it were a function name and appending a list of arguments to it. If the function being called takes no input arguments then empty parentheses are required after the function handle name. Consider the function fd_deriv in Listing 10.1. This function evaluates the finite difference approximation ƒ (x+h)−ƒ (x) h ≈ ƒ′ (x) to the function passed as its first argument. When we type ≫ fd_deriv (@sqrt, 0.1) ans = 1.5811 the first f call in fd_deriv is equivalent to sqrt (x+h). We can use our Newton square root function sqrtn (Listing 7.5) instead of the built-in square root: ≫ fd_deriv(@sqrtn, 0.1) k x_k rel. change 1: 5.5000000745058064e-001 8.18e-001 % Remaining output from sqrtn omitted.

Read the paper · More papers on PaperTik