Nested Functions
MATLAB allows one or more functions to be completely nested within another function. To define a nested function, you must add the <span>end</span>
statement at the end of the nested function and the main function (otherwise, they are local functions), and a good coding style is to add indentation for nested functions.
Nested functions have two key characteristics:
-
Nested functions can access the workspace of the function they are in. -
The function handle of a nested function stores the information needed to access the nested function, as well as the values of all external scope variables required to evaluate the nested function (i.e., variables in the containing function), which are necessary for evaluating the nested function.
An example of a nested function is shown below.
The function <span>rational_ex</span>
contains the nested function <span>r</span>
function rational_ex(x)
% RATIONAL_EX Nested function example
a = 1; b = 2; c = 1; d = -1;
fd_deriv(@rational, x)
function r = rational(x)
% Rational function
r = (a + b * x) / (c + d * x);
end
end
In this example, <span>rational_ex</span>
uses <span>fd_deriv</span>
.
The function <span>fd_deriv</span>
function y = fd_deriv(f, x, h)
% FD_DERIV Finite difference approximation of derivative
% FD_DERIV(f, x, h) is the finite difference approximation of the derivative of function f at x,
% with a difference parameter h. By default, h is sqrt(eps).
if nargin < 3, h = sqrt(eps); end
y = (f(x + h) - f(x)) / h;
This example illustrates how to pass a parameter-dependent function to another function. In the body of <span>rational_ex</span>
, the function handle of the nested function <span>rational</span>
is passed to <span>fd_deriv</span>
. The variables <span>a</span>
, <span>b</span>
, <span>c</span>
, and <span>d</span>
in the workspace of the main function can be accessed in <span>rational</span>
, and their values are encapsulated in the function handle passed to <span>fd_deriv</span>
. Even though these four variables are not in the scope of <span>fd_deriv</span>
, the function can still correctly evaluate <span>rational</span>
based on the values of the variables at the time the function handle was created:
>> rational_ex(2)
ans =
3.0000
This example could also be rewritten using an anonymous function, as shown in the example of <span>sqrtn</span>
from the previous article. However, the method of anonymous functions is limited to functions defined by a single expression. The advantage of nested functions is that they allow you to write a complete function containing nested functions to solve a complete problem involving parameterized functions; we will extensively use nested functions later.
For precise scope rules regarding nested functions, you can also refer to the MATLAB documentation.