Programming Previous page   Next Page

Examples of Nested Functions

This section shows a few examples of how you can use nested functions. These examples are intended to show you how to program with this type of function. For more mathematically oriented examples, see the MATLAB Mathematics documentation.

The examples in this section include

Example 1 -- Creating a Function Handle for a Nested Function

The following example constructs a function handle for a nested function and then passes the handle to the MATLAB fplot function to plot the parabola shape. The makeParabola function shown here constructs and returns a function handle fhandle for the nested parabola function. This handle gets passed to fplot:

Assign the function handle returned from the call to a variable (h) and evaluate the function at points 0 and 25:

Now pass the function handle h to the fplot function, evaluating the parabolic equation from x = -25 to x = +25:

Example 2 -- Function-Generating Functions

The fact that a function handle separately maintains a unique instance of the function from which it is constructed means that you can generate multiple handles for a function, each operating independently from the others. The function in this example makes IIR filtering functions by constructing function handles from nested functions. Each of these handles maintains its own internal state independent of the others.

The function makeFilter takes IIR filter coefficient vectors a and b and returns a filtering function in the form of a function handle. Each time a new input value xn is available, you can call the filtering function to get the new output value yn. Each filtering function created by makeFilter keeps its own private a and b vectors, in addition to its own private state vector, in the form of a transposed direct form II delay line:

This sample session shows how makeFilter works. Make a filter that has a decaying exponential impulse response and then call it a few times in succession to see the output values change:

As an extension of this example, suppose you were looking for a way to develop simulations of different filtering structures and compare them. This might be useful if you were interested in obtaining the range of values taken on by elements of the state vector, and how those values compare with a different filter structure. Here is one way you could capture the filter state at each step and save it for later analysis:

Call makeFilter with inputs v1 and v2 to construct function handles to the iirFilter and getState subfunctions:

Call the iirFilter and getState functions by means of their handles, passing in random values:


Previous page  Using Function Handles with Nested Functions Subfunctions Next page

© 1994-2005 The MathWorks, Inc.