How to Delete a Variable in MATLAB

The function clearvars deletes variables, releasing them from system memory.


Create three matrices using the following code:

A = 1; 
B = [1, 2, 3]; 
C = [4, 5; 7, 8];


clearvars deletes all variables in the current workspace. clearvars(var1,var2,…,varN) deletes the variables specified by the strings var1,var2,…,varN.

% Delete the variables A and B
% Delete all variables


The function clear clears items existing in the workspace, including variables. clear deletes all variables in the current workspace. clear(item1,item2,…,itemN) clears the workspace items specified by the strings item1,item2,…,itemN.

% Create two variables
D = 'Hello World!';
E = 9;
% Delete the variable D
% Delete all variables

Note: On UNIX systems, clearvars and clear do not affect the amount of memory allocated to the MATLAB process.

Further reading

I recommend the following books to learn more on the MATLAB environment.

  1. MATLAB: A Practical Introduction to Programming and Problem Solving (4th Edition)

    This book was the winner of a 2017 Textbook Excellence Award. The first chapter explains the windows of the MATLAB environment, among other introductory topics like operators, random numbers, and trigonometry.

  2. MATLAB for Engineers (5th Edition)

    This excellent book is especially oriented to engineers and scientists who want to learn MATLAB programming. The second chapter explains the windows of the MATLAB environment, how to name variables, and how to save a series of commands in an .M file, among other topics.

I also recommend the following pages in the MATLAB help documentation, and the other tutorials in this series.

doc clearvars;
doc clear;

Source code

I hope you have learned how to delete a variable in MATLAB. The source code developed in this tutorial is available at this page.


Your friends may need this knowledge to complete a task. Share this tutorial.