To clear variables in MATLAB, use the clear or clearvars command in the Command Window, a script, or a function. For example, clear x removes the variable x from the current workspace, while clear removes all variables from that workspace. You can also keep selected variables, clear names that match a pattern, and check what remains afterward. Choosing the right command helps you avoid deleting data you still need.
How to Clear Variables in MATLAB
The quickest way to remove a variable in MATLAB is to use clear followed by its name. Separate multiple variable names with spaces:
clear x
clear x y results
These commands remove the specified variables from the current workspace. If a name is not present, MATLAB generally does nothing for that name. To remove every variable from the current workspace, enter:
clear
This is useful when you want to start a fresh calculation or prevent old values from affecting a new run. Be aware that clearing variables is not the same as closing figures, clearing the Command Window, or deleting files. Each of those actions uses a different command.
Use clearvars for More Control
clearvars is a flexible command for clearing variables. With no options, it clears variables from the current workspace, much like clear:
clearvars
You can also specify exactly which variables to remove:
clearvars x y results
For scripts and analysis workflows, clearvars can make your intent easier to read, especially when you are using options to keep or select variables. It affects the workspace where it runs. In a script, that is typically the workspace from which the script was called; in a function, it is that function’s local workspace.
Clear All Variables Except Selected Ones
If you want a clean workspace but need to preserve a few important values, use the -except option with clearvars. List the names you want to keep after the option:
clearvars -except data settings
In this example, MATLAB removes other variables from the current workspace but retains data and settings. This can be helpful when a long-running calculation has already loaded a large dataset, or when you want to clear temporary results without reloading configuration values.
Check the spelling of every name you want to preserve. If a name is misspelled or does not exist, it cannot be kept. When you are unsure what is currently in the workspace, run whos first to display variables and details such as their sizes and classes.
Clear Variables by Name Pattern
When a workspace contains many similarly named temporary variables, clearvars -regexp can remove variables whose names match a regular expression. For example, this command clears names that begin with temp:
clearvars -regexp '^temp'
The expression ^temp means “starts with temp.” It could match names such as temp1, temp_data, and temporaryResult. You can use other regular expressions to select names by prefix, suffix, or pattern. Since a pattern may match more variables than expected, inspect the workspace with whos before running a broad cleanup command.
Clear Variables in the MATLAB Workspace
MATLAB has different workspaces, so it matters where a command runs. The base workspace is commonly used by commands entered in the Command Window and by scripts run from it. Functions have their own local workspaces, which contain their input arguments and local variables.
Running clear x in the Command Window removes x from the base workspace. Running the same command inside a function affects the function’s local variable named x, not a variable with the same name in the base workspace. When the function finishes, its local variables normally go out of scope anyway.
Scripts generally run in the workspace from which they are called. As a result, a clear command inside a script can remove variables in that workspace. Use care when adding broad commands such as clear to reusable scripts: they may delete values that a user created before running the script.
Clear Variables in a Script or Live Script
To clear variables automatically at the start of a script, put a command near the top:
clearvars
% Continue with the analysis
For a script that should preserve inputs or configuration values, specify them with -except instead:
clearvars -except inputData options
This can help make a script’s results more reproducible by reducing the chance that leftover variables from an earlier run will affect the current run. However, it is often better to write scripts that initialize the variables they use and do not depend on an unpredictable workspace. Avoid clearing everything automatically if the script is meant to work with variables prepared by the user.
The same principle applies to MATLAB Live Scripts. A Live Script can run sections independently, so a variable created in one section may remain available when you run another. If you need a fresh state, use a deliberate cleanup command or run the entire Live Script from the beginning. Remember that clearing a variable may cause later sections to fail if they rely on it.
What Is the Difference Between clear and clear all?
clear removes variables from the current workspace. By contrast, clear all performs a broader cleanup, removing variables and clearing loaded functions and other in-memory items, including persistent data in functions. That broader action is rarely necessary just to remove ordinary workspace variables.
Prefer targeted commands such as clear x or clearvars for routine work. clear all can make MATLAB reload functions the next time they are used, which may slow execution. It can also disrupt state that you intended to retain. Use it only when you specifically need a more extensive reset, such as when testing behavior that depends on a function’s persistent state.
If you need to reset a particular function rather than clear every variable, you can clear that function by name:
clear myFunction
Clearing a function can remove its persistent variables, so the function starts with fresh persistent state the next time it runs. This is different from deleting a variable in the base workspace.
Clear Global and Persistent Variables
Global variables are shared between the workspaces that declare them with the global command. To clear a named global variable, use:
clear global sharedValue
To clear global variables more broadly, use clear global. Because global variables can be accessed from multiple functions, clearing one may affect other parts of your program. Use globals sparingly and check how they are used before removing them.
Persistent variables are stored between calls to the function that defines them. They are not ordinary base-workspace variables, so clear x in the Command Window will not reset a persistent variable named x inside a function. Clear the function that owns the persistent variable to reset its stored state:
clear myFunction
If MATLAB cannot clear a function because it is currently in use, finish or exit the relevant execution before trying again.
How to Confirm That Variables Were Cleared
Use whos to list variables in the current workspace, including their sizes and data types. For a simpler list of names, use who:
who
whos
If a variable name no longer appears, it has been removed from that workspace. You can also test whether a variable exists with exist:
exist('x', 'var')
For a workspace variable, a result of 1 indicates that the variable exists, while 0 indicates that it does not. The check applies to the workspace in which the command runs, so a variable in a function may not be visible from the Command Window.
Common Mistakes When Clearing MATLAB Variables
-
Using clear all by default: It does more than remove workspace variables and can cause functions to reload. Use
clearorclearvarsfor everyday cleanup. - Clearing a variable before using it: If later code depends on that variable, the code may produce an undefined-variable error. Confirm what a script needs before adding cleanup commands.
- Assuming every workspace is the same: A command in a function acts on that function’s local workspace, not automatically on the base workspace.
-
Confusing clear with clc:
clearremoves variables;clcclears visible text from the Command Window. The two commands do different things. -
Using a broad regular expression without checking: A pattern may match important variables as well as temporary ones. Inspect names with
whoorwhosfirst.
Conclusion
To clear variables in MATLAB, use clear name to remove specific variables, clear or clearvars to empty the current workspace, and clearvars -except to keep selected values. Use clearvars -regexp for carefully chosen name patterns, and remember that functions, scripts, global variables, and persistent data have different workspace behavior. For most everyday cleanup, a targeted clear or clearvars command is safer than clear all. Check the result with who or whos before continuing your analysis.
Disclaimer: Articles are written by Humans, AI or Both. Verify Important information.