This HTML version of the book is provided as a convenience, but some math equations are not translated correctly. The PDF version is more reliable. ## Chapter 16 Nested FunctionsThis appendix provides an alternative way to structure code that involves helper functions, which were discussed in Section 8.1; there, we saw an example of an M-file with more than one function: function res = duck() error = error_func(10) end function res = error_func(h) rho = 0.3; % density in g / cm^3 r = 10; % radius in cm res = ... end Because the first function ends before the second begins, these functions are at the same level of indentation. Functions like these are parallel, as opposed to nested. A nested function is defined inside another, like this: function res = duck() error = error_func(10) function res = error_func(h) rho = 0.3; % density in g / cm^3 r = 10; % radius in cm res = ... end end The function duck is the enclosing function and error_func is the nested function. Nesting functions is useful because the variables of the outer function can be accessed from the inner function. This is not possible with parallel functions. In this example, using a nested function makes it possible to move the parameters rho and r out of error_func. function res = duck(rho) r = 10; error = error_func(10) function res = error_func(h) res = ... end end Both rho and r can be accessed from error_func. By making rho an input argument, we made it easier to test duck with different parameter values. Nested functions can also help de-clutter code (but not always). For more information on nested functions, please consult the official documentation at https://www.mathworks.com/help/matlab/matlab_prog/nested-functions.html. |
## Are you using one of our books in a class?We'd like to know about it. Please consider filling out this short survey. |