Programming

Nested Functions

You can define one or more functions within another function in MATLAB. These inner functions are said to be nested within the function that contains them. You can also nest functions within other nested functions.

This section covers the following topics on using nested functions in MATLAB:

Writing Nested Functions

To write a nested function, simply define one function within the body of another function in an M-file. Like any M-file function, a nested function contains any or all of the components described in Basic Parts of an M-File. In addition, you must always terminate a nested function with an `end` statement:

• ```function x = A(p1, p2)
...
function y = B(p3)
...
end
...
end
```

 Note    M-file functions don't normally require a terminating `end` statement. This rule does not hold, however, when you nest functions. If an M-file contains one or more nested functions, you must terminate all functions (including subfunctions) in the M-file with `end`, whether or not they contain nested functions.

Example -- More Than One Nested Function

This example shows function `A` and two additional functions nested inside `A` at the same level:

• ```function x = A(p1, p2)
...
function y = B(p3)
...
end

function z = C(p4)
...
end
...
end
```

Example -- Multiply Nested Functions

This example shows multiply nested functions, `C` nested inside `B`, and `B` in `A`:

• ```function x = A(p1, p2)
...
function y = B(p3)
...
function z = C(p4)
...
end
...
end
...
end
```

 Primary M-File Functions Calling Nested Functions