Nested Functions
In this section...
“What Are Nested Functions?” on page 20-27
“Requirements for Nested Functions” on page 20-27
“Sharing Variables Between Parent and Nested Functions” on page 20-28
“Using Handles to Store Function Parameters” on page 20-29
“Visibility of Nested Functions” on page 20-31
What Are Nested Functions?
A nested function is a function that is completely contained within a parent function. Any function in
a program file can include a nested function.
For example, this function named parent contains a nested function named nestedfx:
function parent
disp('This is the parent function')
nestedfx
function nestedfx
disp('This is the nested function')
end
end
The primary difference between nested functions and other types of functions is that they can access
and modify variables that are defined in their parent functions. As a result:
• Nested functions can use variables that are not explicitly passed as input arguments.
• In a parent function, you can create a handle to a nested function that contains the data necessary
to run the nested function.
Requirements for Nested Functions
• Typically, functions do not require an end statement. However, to nest any function in a program
file, all functions in that file must use an end statement.
• You cannot define a nested function inside any of the MATLAB program control statements, such
as if/elseif/else, switch/case, for, while, or try/catch.
• You must call a nested function either directly by name (without using feval), or using a function
handle that you created using the @ operator (and not str2func).
• All of the variables in nested functions or the functions that contain them must be explicitly
defined. That is, you cannot call a function or script that assigns values to variables unless those
variables already exist in the function workspace. (For more information, see “Resolve Error:
Attempt to Add Variable to a Static Workspace.” on page 20-33.)
Nested Functions
20-27
Précédent

- 735/1450

Suivant