Tutorial

Visibility of Nested Functions in MATLAB

Functions contained within another function are called “nested functions”.

Rules

A function is visible in a given context if it can be called from that context. In MATLAB, a nested function is visible from:

  1. Its parent —the function immediately above it
  2. Its siblings —the functions nested at the same level within the same parent
  3. Any function at a level lower than its level in the same hierarchy
The scope of a function is the set of other functions to which it is visible.

Example

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
  • main can call nested1 and nested2, but not nested3
  • nested1 can call nested2 and main, but not nested3
  • nested2 can call all other functions
  • nested3 can call all other functions

Further reading

I recommend the following books to learn more on functions in MATLAB.

  1. MATLAB: A Practical Introduction to Programming and Problem Solving (4th Edition)

    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.

  2. 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.

web(fullfile(docroot, 'matlab/matlab_prog/nested-functions.html'));

Exercise

Suppose the following code:

function big()
    function nested1()
        function nested2()
        end
        function nested3()
            function nested4()
            end
        end
    end
end
  1. Can nested2 call nested4?
  2. Can nested1 call nested3?
  3. Can nested3 call nested2?

Source code

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.

Share

Your friends may need this knowledge to complete a task. Share this tutorial.