Kahibaro
Discord Login Register

Clearing Variables and Managing the Workspace

Overview

In everyday MATLAB work you will constantly create, modify, and remove variables. Over time your workspace can fill up with many variables that you no longer need. This can cause confusion, unexpected results, and performance issues. In this chapter you will learn how to clear variables in a controlled way, how to reset parts of your environment, and how to manage the workspace so that your scripts and functions behave predictably.

Clearing Variables with `clear`

The central command for removing variables from the workspace is clear. In its simplest form, typing clear in the Command Window removes all variables from the current workspace. After this, whos will show an empty list of variables.

If you want to remove only specific variables, you can pass their names as arguments. For example, if you have variables a, b, and result, and you want to keep result but remove a and b, you can write:

matlab
clear a b

You can pass as many variable names as you want in a single clear command. Any variable whose name you list will be removed. If you try to clear a name that does not exist, MATLAB simply ignores it without error.

Sometimes you want to remove all variables that match a pattern. For this, clear supports wildcards using the * character. For example, if you have variables temp1, temp2, and temperature, you can clear only the temp variables with:

matlab
clear temp*

This removes temp1 and temp2 but leaves temperature. Wildcards are useful when you follow naming conventions and want to clean up a certain group of variables.

Clearing Functions and Persistent State

Besides variables, clear can also affect functions and their internal state. When you call a user defined function that uses persistent variables, those persistent values are kept between calls until the function is cleared. Using clear functionName removes the function from memory and resets its persistent variables. The next time you call the function, it behaves as if it is being called for the first time in that MATLAB session.

You can also use:

matlab
clear functions

to clear all loaded functions from memory. This does not remove the function files from disk. It simply causes MATLAB to reload them when they are called again. This is helpful when you have edited function files and want to ensure MATLAB uses the new versions.

By default, a plain clear without arguments removes variables but does not clear functions. MATLAB provides this separation so that you can reset the workspace without forcing every function to reload.

Clearing Classes and Other Special Forms

If you work with custom classes, MATLAB may keep compiled information about them in memory. When you change a class definition file, you may need to clear the class definition so MATLAB can load the new version. The command:

matlab
clear classes

forces MATLAB to remove all class definitions from memory. The next time you create an object of a class, MATLAB reads the updated class file.

Finally, the command:

matlab
clear all

combines several clearing behaviors. It removes variables, functions, and some cached state from memory. It is stronger and slower than clear and is usually not needed in normal interactive work. Many beginners place clear all at the top of every script. This often adds unnecessary overhead and can interfere with performance. In many situations, clear or clearvars is a better and more controlled choice.

Using `clearvars` for Fine Control

MATLAB provides the clearvars function for more flexible workspace management. While clear works with both variables and functions, clearvars focuses strictly on variables in the current workspace.

The simplest use is:

matlab
clearvars

which removes all variables from the current workspace, similar to clear. However, clearvars has options that allow you to specify what to clear or what to keep.

One useful pattern is to keep certain important variables while removing all others. For example, if you want to keep only the variable config and remove everything else, you can write:

matlab
clearvars -except config

The -except option tells MATLAB to preserve the listed variables and clear all others. You can list more than one variable after -except.

You can also remove variables whose names match a pattern using the -regexp option. For instance, to clear all variables whose names start with temp or old, you can write:

matlab
clearvars -regexp ^temp ^old

The patterns are regular expressions that match variable names. This allows more precise control than the simple wildcard * that clear uses. You can combine -except and -regexp carefully to target exactly the variables you want to remove, while keeping others in place.

Workspace vs Function Workspaces

The commands clear and clearvars operate on the current workspace. In the Command Window, this is the base workspace that you see in the Workspace browser. Inside a function, the current workspace is that function's private workspace. If you call clearvars inside a function, it clears variables only inside that function, not in the base workspace.

This separation is important. A script shares the base workspace with the Command Window, so a clear in a script affects variables you created at the command line. A function, in contrast, has its own workspace and cannot accidentally clear variables in the base workspace using clearvars or clear without special measures. This design helps keep your workspaces isolated and predictable when you work with functions.

If you specifically want to clear the base workspace from within a function, you can use:

matlab
evalin('base','clearvars')

However, this kind of cross workspace manipulation is rarely needed for beginners and often makes code harder to understand and debug.

Managing the Workspace with the Desktop

Besides typing commands, you can manage variables using the Workspace browser in the MATLAB desktop. The Workspace browser shows all variables in the current base workspace, along with their sizes, types, and values. To remove a variable from the workspace using the graphical interface, you can right click the variable and select the option to delete it. You can select multiple variables and delete them at once.

The Workspace browser also has options in its context menus and toolbar for clearing all variables. These actions perform the same operations as the equivalent commands but provide a more visual approach. As you clear variables, you will see them disappear from the list, which can help you understand what is stored in memory at any moment.

In more advanced use, you can open variable editors from the Workspace browser to inspect values before deciding whether to clear them. This allows you to check whether a variable still matters for your current task. For simple workflows, combining visual inspection with occasional manual clearing keeps your workspace tidy.

Avoiding Unnecessary Clearing in Scripts

Beginners often place clear all or clear at the top of every script by habit. While this guarantees that the script does not accidentally depend on previously defined variables, it also has costs. Repeatedly clearing everything makes interactive work less efficient because values you may want to reuse are lost. Clearing functions or class definitions unnecessarily can also slow down execution because MATLAB must reload and recompile them.

A more balanced approach is to identify which variables really need to be reset and clear only those. For example, if a script creates data, results, and summary, and you want to ensure these are fresh each time, you can write:

matlab
clearvars data results summary

This keeps other useful variables intact. As your scripts become larger and more permanent, it is usually better to design them so that they do not rely on pre existing variables in the base workspace at all. This reduces the need for aggressive clearing and makes the scripts easier to reuse.

In many cases, turning scripts into functions is a more robust solution, because each function call starts with a clean workspace by design. When you reach the stage of writing functions routinely, you will often find that you no longer need to clear variables manually in the same way.

Resetting the Command Window and Environment

Managing the workspace is part of managing the overall MATLAB environment. If you want a visual reset of the Command Window, but not the variables, you can use:

matlab
clc

This clears the command history displayed in the Command Window, but leaves the workspace unchanged. You can combine clc, clear, and related commands when you want to start a new task with a clean view and clean variables.

If you want an even more complete reset, you can close open figure windows with:

matlab
close all

so that previously created plots do not clutter your screen. A common pattern for starting a completely fresh session within the same MATLAB process is:

matlab
clc
clearvars
close all

This keeps MATLAB itself running while clearing the Command Window, variables, and figures. Use this only when you are sure you do not need the existing data.

Using `who` and `whos` Before Clearing

Before removing variables, it can be helpful to review what is currently in the workspace. The commands who and whos display lists of variable names, with whos providing more detailed information such as size, bytes, and class. For example:

matlab
whos

might show a list of large data arrays. If certain variables consume a lot of memory and you no longer need them, you can selectively clear those to free memory without discarding everything.

You can combine who with patterns to check which variables will be affected by a future clear. For instance:

matlab
who temp*

lists all variables whose names start with temp. After confirming the list, you can run clear temp* with confidence. This preview helps avoid accidental loss of important variables.

Managing Memory and Performance

When working with large datasets, managing the workspace is closely linked to managing memory. Every variable occupies space in memory. If you create several large arrays and keep them all around, you may run into memory limits or see MATLAB slow down. Clearing variables that you no longer need can free memory and improve responsiveness.

However, clearing too often can also hurt performance. Creating and destroying large variables repeatedly can be costly. If a variable is reused frequently, it may be better to overwrite its content rather than clear it and recreate it from scratch. For example, updating data in place using new values avoids the overhead of clearing and reallocating.

If you notice that MATLAB reports memory problems, look in the Workspace browser or use whos to see which variables are large. Clear only those that are unnecessary. This targeted approach is more efficient than always clearing everything.

Persistent Workspace vs New Sessions

The MATLAB workspace persists for as long as the MATLAB session is open. When you close MATLAB, all variables are lost unless you save them to a MAT file. When you restart MATLAB, the workspace starts empty unless you explicitly load data.

If you want a completely clean environment, with no variables, no open figures, and no residual state, closing and reopening MATLAB will provide this. Within a single session, using clearvars, clc, and close all gives you a reset that is often sufficient for interactive work. Understanding the difference between clearing within a session and starting a new session helps you choose the right level of reset for your situation.

Key points to remember:
Use clear or clearvars to remove variables, and prefer targeted clearing over clear all.
clearvars -except name1 name2 is useful when you want to keep only a few important variables.
Commands act on the current workspace, which is the base workspace in the Command Window and a private workspace inside functions.
Use whos and the Workspace browser to inspect variables before clearing, especially when memory is a concern.
Avoid placing clear all at the top of every script, and move toward writing functions to reduce reliance on manual clearing.

Views: 3

Comments

Please login to add a comment.

Don't have an account? Register now!