Loren on the Art of MATLAB

Turn ideas into MATLAB


Loren on the Art of MATLAB has been archived and will not be updated.

Nested Functions and Variable Scope

I get a parade of questions about which variables are available to nested functions and which variables, used in nested functions, are part of the nesting function workspace. So today I thought I'd address this topic. For more information, you can read this documentation.  


Where is data?

Let's take a look at the following code.
function blahblah
% BLAHBLAH help line
data = 1;
data2 = yoyo1();
   function data = yoyo1()
       % Note that data is an output here
       data = 2
   function yoyo2(in)
      % Here, data is shared with the variable 'data'
      % in blahblah's workspace
      data = in;
You can see that there is the variable, in each function, named data. The question is, however, do they all refer to the same entity? And the answer is 'no.' Surprised? Let me explain. yoyo1 essentially declares data to be a local variable and not shared because of data's presence on the output argument list. The same would be true if data showed up on the input argument list instead, or if it showed up on both. However, yoyo2, which has no mention of data in its arguments lists, shared the variable data that is in blahblah's workspace. So calling yoyo2 changes the value of data in blahblah but calling yoyo1 does not.

Truisms about Variable Scope with Nested Functions

  • When you call an M-file containing a nested function, sufficient analysis is done on the M-file to determine which variables are shared and which functions share them.
  • If a variable is in a nested function and appears in at least one of input or output argument lists for that function, then, even if it's name matches a name in the nesting function's workspace, the two variables refer to different entities. This is true even if other nested functions share the variable in the nesting function.
  • For a variable in a nested function to be shared with the nesting function, the variable must appear in the code of (i.e., be referred to or used in) nesting function. This is true even if you don't need to use the variable in the nesting function but want multiple nested functions to share the variable.
  • You can't poof variables into nested function workspace. If need to do some debugging and want to create new variables, you can declare them global and then assign to them. For more detail, read the documentation about Restrictions on Assigning to Variables.

Your Thoughts?

In the code I showed, I made sure to highlight the variables that are shared by printing them in italic. Especially for those of you who do not care for the implementation we chose for nested functions, would some visual affordance such as this make the situation more tenable for you? Let me know here.

Published with MATLAB® 7.5

  • print


To leave a comment, please click here to sign in to your MathWorks Account or create a new one.