Use of Nested Functions

Nested functions allow the child functions to access their parent functions’ variables as long as they are declared in the parent function. Let us see the same through the following example.

Example 2:

Matlab




% MATLAB Code
sqr
 
% Function
function sqr
    num = 3;
    work_function
    
   % Child function to calculate and
   % display the square of the num
    function work_function
        num=num*num;
        dip(num)
    end
end


Output:

In the above function, we declare a variable num and then calculate and display its square within a child function. See the output below.

 

Share Data Between Workspaces in MATLAB

Workspaces in MATLAB are the scopes of a particular code entity such as a function. In general, data cannot be shared between two workspaces or, one can say that a data variable created in one workspace cannot be accessed by some other workspace, without additional support. In this article, we shall discuss this very additional support or ways in which data can be shared by different workspaces. For implementation purposes, this article uses functions to represent different workspaces. However, different scripts or live scripts also are types of different workspaces. 

Let us now understand the ways to share data/variables among workspaces in MATLAB.

Similar Reads

Use of Function Arguments:

As it is a standard practice to use input and output arguments in MATLAB functions, they are also the best way to share data between two different functions. Following is an example of the same....

Use of Nested Functions:

...

Using Global Keyword:

Nested functions allow the child functions to access their parent functions’ variables as long as they are declared in the parent function. Let us see the same through the following example....

Using PERSISTENT Variables:

...

Evaluating in another workspace

When a variable is initialized using the global keyword in any workspace, it becomes accessible to all functions/workspaces in the current session. See the following example....