Variable Scope: Memory Spaces in Matlab

For this post, we are glad to welcome Nicholas as a contributor to Matlabtips.com. If you are interested in writing a guest post, please don’t hesitate to contact us.

In this post, we talk about variables. In particular, we will explain where variables “sit” in memory depending on where you declared it (within a script or a function). This is a very important post if you are learning the language.

One of the first things to learn about Matlab is where the variables you define “live” within the Matlab ecosystem. The scope of your variables is essentially which part of your programs (e.g. sub-functions or other scripts) has access to those variables.

One important concept that you should understand off the bat is the difference between a script and a function. As we will see later, this has a significant effect on how the variables defined within these two different types of files can be accessed in your Matlab programs

In the above picture, test_script.m is a script while test_function.m is a function – not too bad so far, huh? By adding the function keyword in the test_function.m file, we designate that file as a function. You can easily tell which files are functions and which are scripts due to their different icons shown in the Current Folder window.

Now, when we execute these files, things start to get interesting. I will execute both test_function.m and test_script.m and show you the output in workspace window:

Output from test_script.m

Output from test_function.m

The output from the script should look how you would expect it – all the variables defined within the script are listed in the workspace. Meanwhile, after running the function, we only see this variable called ans in the workspace. Why did this happen? Really there are two answers here. First, why the heck is ans in the workspace variables? Well, when you run a function and do not assign an output to that function, Matlab will automatically make that output a variable called ans – short for answer. Conversely, I could call test_function from within a script or from the command window and assign an output to that function:

new_output = test_function()

If I did this, rather than ans being in the workspace variables, new_output would be there.

The second question (and the heart of this post) is why the other variables in test_function.m including test2 and ret_value are not included in the workspace window. The answer to that is each variable’s scope. Within a function each variable is defined as a localvariable. This means that it can only be accessed within that particular function. This is in contrast to a workspace variable, which is defined in either a script or in the command window. Here is a graphic to explain this in visual form.

As you can see, workspace variables can be used (i.e. accessed) in either the command window or in scripts, while local variables are defined within and can only be accessed within a given function. Here is a breakdown of the main difference between these two variable types:

Workspace Variables: Defined and can be accessed in a script or in the command window. These variables will be shown in the workspace window within the Matlab environment. These variables will continue to exist “in the workspace” until you close Matlab or specifically tell Matlab to delete these variables (more on that in a bit).

Local Variable: Defined within a function and may only be accessed or modified within that same function. These variables will be created in Matlab’s memory only when the function is called and will be removed from its memory once the function call is complete.

How to remove workspace variables – As you now know, workspace variables will exist in Matlab until you close the program or specifically tell Matlab to delete that variable. In order to remove a given variable in your Matlab workspace you would write the following (in either a script or Command Window):

clear your_variable_here

If you would like to remove ALL variables from your workspace, you would execute the following command:

clear all

Another useful command to know when using workspace variables is the whocommand. This command will return a list of all your workspace variables. This may be useful in a scenario in which you would like to see if a specific variable is already defined.

Workspace and local variables are two of the most common types of variables in Matlab, but there also exists more advanced variable types to bypass the functionality of workspace and local variables.

Persistent Variables – These types of variables are used in functions and are still local to that function, but the main distinction between these variables and regular old local variables is that persistent variables are not removed from Matlab’s memory after the function call. Essentially, these variables remain in Matlab’s memory, so a particular function can know information about the last time this function ran.

Global Variables – Global variables can be accessed anywhere in Matlab – scripts, functions, and the Command Window. You must define the variable as global in any script or function that you wish to use it, including the Command Window. This means that you can define a global variable in a script then work directly on that variable within a function without passing it as an argument.

Here is a quick example to see these in action. This is a very high level control structure for a small ground robot with a bump sensor. What we aim to do is go straight until we hit an object then we try to back up. If we cannot back up (e.g. we are stuck), we will try again slowly and make a notification sound.

You can see in the above script how emergency_stop is defined as a global variable in every script or function that we wish to access it. You can also see how the persistent variable last_bump is used to determine the whether the robot was touching something during the last call to the velocity_control function.

Global variables have a very bad reputation among professional programmers. A reason for that lies in the difficulty to track bugs with such variables as they basically affect all parts of your program. It is generally recognized that global variables can always be avoided with careful design of your program structure and the interdependencies of your functions. This being said, Matlab is often used to test out ideas quickly and global variables can allow you not to worry about your variable scope and focus on an immediate data analysis problem.

A last quick and dirty but useful usage of global variable is when you are dealing with VERY LARGE matrices. Variables that are passed to sub-function are typically duplicated in memory so you can bypass this problem by using globals. If you ever consider this option, I invite you to read this post and also this one.

By the end of this post, you should know the main differences between a workspace variable and a local variable and how Matlab handles both of these. This is an important concept in programming so make sure you read this post until you get it.