A function is visible in a given context if it can be called from that context. In MATLAB, a nested function is visible from:
- Its parent —the function immediately above it
- Its siblings —the functions nested at the same level within the same parent
- Any function at a level lower than its level in the same hierarchy
This example is merely for illustrative purposes. In real-life applications, try to keep to number of levels as low as possible. A high number of levels makes the code difficult to understand and maintain.
function main() function nested1() end function nested2() function nested3() end end end
nested2, but not
main, but not
nested2can call all other functions
nested3can call all other functions
I recommend the following books to learn more on functions in MATLAB.
This book was the winner of a Textbook Excellence Award. The sixth chapter covers user-defined functions, scope of variables, debugging, and other aspects related to the development of MATLAB programs.
MATLAB for Engineers (5th Edition)
This excellent book is especially oriented to engineers and scientists who want to learn MATLAB programming. Chapter 6 explains how to create functions, including nested functions, anonymous functions, and local functions.
I also recommend the following page in the MATLAB help documentation, and the other tutorials in this series.
- How to Define Functions in MATLAB
- How to Call a Function in MATLAB
- How to Add Help Documentation to a Function in MATLAB
- Local Functions in MATLAB
- Nested Functions in MATLAB
- Visibility of Nested Functions in MATLAB
- Private Functions in MATLAB
- Anonymous Functions in MATLAB
- Inside the Handle of Anonymous Functions in MATLAB
- Functions with Variable Input Arguments in MATLAB
- Functions with Variable Output Arguments in MATLAB
- How to Validate the Number of Input Arguments Passed to a Function in MATLAB
- How to Validate the Number of Output Arguments Passed to a Function in MATLAB
Suppose the following code:
function big() function nested1() function nested2() end function nested3() function nested4() end end end end
The answer to each question is:
- No, it cannot
- Yes, it can
- Yes, it can
I hope you have understood the rules that govern the visibility of nested functions in MATLAB. The source code developed in this tutorial is available at this page.