Documentation Center

  • Trial Software
  • Product Updates

Variables in Nested and Anonymous Functions

The scoping rules for nested and anonymous functions require that all variables used within the function be present in the text of the code.

If you attempt to dynamically add a variable to the workspace of an anonymous function, a nested function, or a function that contains a nested function, then MATLAB® issues an error of the form

Attempt to add variable to a static workspace. 

This table describes typical operations that attempt dynamic assignment, and the recommended ways to avoid it.

Type of Operation

Best Practice to Avoid Dynamic Assignment

load

Specify the variable name as an input to the load function. Or, assign the output from the load function to a structure array.

eval, evalin, or assignin

If possible, avoid using these functions altogether. See Alternatives to the eval Function.

Calling a MATLAB script that creates a variable

Convert the script to a function and pass the variable using arguments. This approach also clarifies the code.

Assigning to a variable in the MATLAB debugger

Create a global variable for temporary use in debugging, such as

K>> global X;
K>> X = myvalue;

Another way to avoid dynamic assignment is to explicitly declare the variable within the function. For example, suppose a script named makeX.m assigns a value to variable X. A function that calls makeX and explicitly declares X avoids the dynamic assignment error because X is in the function workspace. A common way to declare a variable is to initialize its value to an empty array:

function noerror
X = [];
nestedfx

   function nestedfx
      makeX
   end
end

More About

Was this topic helpful?