Scope of variables in MATLAB
Variable scope refers to the extent of the code in which a variable can be referenced, accessed or modified, without resulting in an access error. We have already discussed that variables inside functions are local to the functions and not visible to other functions in MATLAB. Variables defined inside a function are called local variables. They reside in the corresponding workspaces of the functions. The scope of local variables and dummy arguments is limited to the function (that is, to their workspace) in which they are defined. If the function contains nested functions, the code in the nested functions can access all variables defined in their parent function.
Occasionally it is convenient to create variables that exist in more than one workspace including, possibly, the main workspace. This can be done using the global statement. Variables stored in the MATLAB workspace (i.e., global memory) are called global variables.
Global vs local variables
Frequently, we need data (variable) protection (encapsulation) provided by local variables defined inside functions. In general, you should always do your best to avoid using global variables everywhere in your codes as much as possible. For small projects and problems, this may not be a significant issue. However, in large scale problems, the use of global variables can cause significant confusion, poor efficiency of your code, and even wrong results!
Occasionally, it may be useful to access global variables from within a function, for example, when the global variables contain large amounts of data and passing them to through the function arguments may lead to significant consumption of computer memory and time.
Global variable usage syntax
- To access a global variable from within a function, one should explicitly label the variable as
- A global variable must be declared global before it is used the first time in a function.
- Global variable declarations should be placed at the beginning of a function definition.
- For making a variable global in MATLAB’s base workspace, you should also first declare it as global.
For example, consider the following code,
function setGlobalx(val) global x x = val; end
>> setGlobalx(10) >> x
Undefined function or variable 'x'.
The problem here is that
x is not declared as global in MATLAB’s base workspace. To do so,
>> global x >> setGlobalx(10) >> x
x = 10
Consider the same
reverseSentence function that we discussed above, but this time instead of giving it an input argument, we want to use a global variable string from MATLAB’s base workspace. How would you implement this, such that the following commands lead to the same output from the new global function?
>> global globalString >> globalString = 'MATLAB is a rather strange but very powerful programming language'; >> reverseSentenceGlobal()
language programming powerful very but strange rather a is MATLAB
function reverseSentenceGlobal() % reverseSentence recursively prints the words in a string in reverse order global globalString getToken(globalString) function getToken(string) [word, rest] = strtok(string); if ~isempty(rest) getToken(rest); end fprintf([word,' ']) end fprintf('\n') end
Sometimes you may need to keep a variable inside a function local, but still, you want the variable to retain its value from the last call of the function in the most recent function call. This is very useful, in particular, makes your code immune to pitfalls of declaring variables
global. The way to it is through the use of
When you declare a variable within a function as persistent, the variable retains its value from one function call to the next. Other local variables retain their value only during the current execution of a function. Persistent variables are equivalent to static variables in other programming languages. Like
global attribute inside functions, you have to declare variables using the
persistent keyword before you use them inside the function. For example, consider the following function that adds an input value to some older value that already exists in the function from the old calls. If it is the first function call, then simply the input value is returned.
function result = findSum(inputvalue) persistent summ if isempty(summ) summ = 0; end summ = summ + inputvalue; result = summ; end
ans = 10
ans = 20
ans = 30
To clean the workspace of the function from these persistent variables, either of the two following methods works,
clear all % danger! clears all objects in the MATLAB workspace. clear <functionName> % clears only this specific function's workspace
To prevent clearing persistent variables, lock the function file using
Here are some advanced general advice by MATLAB developers on defining new variables and the scope of variables in MATLAB functions.
MATLAB functions vs. MATLAB scripts
MATLAB scripts are m-files containing MATLAB statements. MATLAB
functions are another type of m-file, which were comprehensively discussed above. The biggest difference between scripts and functions are the following.
Functions can have input and output parameters. Script files can only operate on the variables that are hard-coded into their m-file.
Functions much more flexible than scripts. They are therefore more suitable for general purpose tasks, or for writing scientific software. Scripts are useful for tasks that don’t change. They are also a way to document a specific sequence of actions, say a function call with special parameter values, that may be hard to remember.
A script can be thought of as a keyboard macro: when you type the name of the script, all of the commands contained in it are executed just as if you had typed these commands into the command window. Thus, all variables created in the script are added to the workspace for the current session. Also, if any of the variables in the script file have the same name as the ones in your current workspace, the values of those variables in the workspace are changed by the actions in the script. This can be used to your advantage. It can also cause unwanted side-effects. In contrast, function variables are local to the function. (with the exception that you could declare and use global variables with explicit
globalattribute.) The local scope of function variables gives you greater security and flexibility. To summarize, the workspace of MATLAB scripts is the base MATLAB workspace, whereas functions have their own individual workspaces.