Programming |
Scope of a Variable
MATLAB stores variables in a part of memory called a workspace. The base workspace holds variables created during your interactive MATLAB session and also any variables created by running M-file scripts. Variables created at the MATLAB command prompt can also be used by scripts without having to declare them as global.
Functions do not use the base workspace. Every function has its own function workspace. Each function workspace is kept separate from the base workspace and all other workspaces to protect the integrity of the data used by that function. Even subfunctions that are defined in the same M-file have a separate function workspace.
Extending Variable Scope
In most cases, variables created within a function are known only within that function. These variables are not available at the MATLAB command prompt or to any other function or subfunction. The most secure way to extend the scope of a function variable is to pass it to other functions as an argument in the function call. Since MATLAB passes data only by value, you also need to add the variable to the return values of any function that modifies its value.
Another way to extend the variable scope is to declare the variable as global
within every function that needs access to it. If you do this, you need make sure that no functions with access to the variable overwrite its value unintentionally.
Scope in Nested Functions
Variables within nested functions are accessible to more than just their immediate function. As a general rule, the scope of a local variable is the largest containing function body in which the variable appears, and all functions nested within that function. For more information on nested functions, see Variable Scope in Nested Functions.
Guidelines to Using Variables | Lifetime of a Variable |
© 1994-2005 The MathWorks, Inc.