How to Clear Variables in MATLAB
This tutorial will discuss clearing variables from memory using the clear
command in Matlab.
Clear Variables From Memory Using the clear
Command in MATLAB
To clear variables from Matlab’s memory or workspace, Matlab provides the built-in command clear. We can use the clear command if we want to clear all the available variables from the Matlab workspace on memory. For example, let’s remove all the variables from the workspace using the clear command. See the code below.
>> clear
You can use the clear
command on the command window as well as in a script file. If we use it at the start of the code, Matlab will clear all the previously stored variables when we run the code. Only the variables generated after the clear
command will be saved in the workspace or memory. If we use the clear command at the end of the code, then all the variables generated during the code’s execution will be removed from the workspace or memory. If we don’t want to clear all the variables, but we want to clear some specific variables, we can use the clear command and the variable’s name to remove that variable from memory. For example, if the variable name is MyMatrix
, we can use the clear command and the MyMatrix
name to clear the variable from memory. For example, let’s create a matrix and then remove it using the clear
command and the variable name. See the code below.
>> MyMatrix = [1 2 3];
>> clear MyMatrix
When you write the first line of code in the command window of Matlab, the variable MyMatrix
will be saved in the workspace. When you write the second line in the command window of Matlab, the variable MyMatrix
will be removed from the workspace or memory. This command will only remove the variable whose name is used, and all other variables will remain in the workspace or memory. You can also write multiple names in a single line separated by a space to remove them from the workspace or memory.
You can also use the item type to remove certain types of items. For example, we can clear all the functions or classes or the variables. The clear
function command will clear all the functions present in the memory, and the clear
class command will remove the classes present in the memory. For example, see the code below.
>>clear functions
If we don’t know the name of certain variables, we can also use expressions, and Matlab will remove the variables that will match the expression. For example, let’s create two variables, MyMatrix
and MyMatrix2
, and remove them using the first name My
. See the code below.
>> MyMatrix = [1 2 3];
>> MyMatrix2 = [1 2 3];
>> clear -regexp ^My
The variables MyMatrix
and MyMatrix2
will be removed from the workspace because they contain My
at the start. You can also write multiple expressions on the same line. Make sure to save certain kinds of results before clearing the variables.