We have heard repeatedly over the years that users would like a tool to help clean up the workspace by choosing selected variables to retain. The function clear, has logic allowing you to clear a selection of variables readily, but it's a bit harder to retain a collection using clear.
Contents
What Does clear Clear?
The function clear, with the all qualifier, can clear just about everything in MATLAB: variables, functions, MEX-files, breakpoints, Java packages import list (from the command prompt). To additionally clear classes, use clear classes.
Debug Gotcha
clear all clears all breakpoints as well as the workspace, and everything else that isn't nailed down (or perhaps mlocked ). This is a frequent source of confusion for people when they are trying to debug code. If the code being debugged issues a clear statement, the breakpoints get cleared and you could be left with a temporary mystery until you chase down the code doing the clearing.
How to Keep Variable Selection
- Use clear with -regexp to remove variables selected from memory.
- Use clearvars -except to retain specific variables in the workspace.
Here's an example of clearing all the variables except those that start with q (the 17th letter of the English alphabet).
a1 = 'Alice'; a2 = 'Ashley'; a3 = 'Alistair'; b1 = 'Barbara'; b2 = 'Brian'; i1 = 'Isobel'; l1 = 'Loren'; q1 = 'Quentin'; q2 = 'Quillan'; r1 = 'Rosie'; r2 = 'Rob'; who
Your variables are: Fs a2 data ind q2 ywav Fswav a3 datadiff l1 r1 N b1 eqFreqs matfiles r2 a1 b2 i1 q1 y
clearvars -except q* who
Your variables are: q1 q2
Your Clear Ideas?
Got any clear ideas? I'd love to hear them; you can post them here.
Get
the MATLAB code
Published with MATLAB® 7.6

I use frequently
clear -regexp ^(?!variable$).
which removes all variables except for the variable I have named there.
I wrote a CLEARALLBUT function years ago.
http://clluengo.lbl.gov/MATLAB/clearallbut.m
I have used it very infrequently, mostly because I keep forgetting I have it.
Nice post Loren. I’m sure this will come in handy for me
Hello Loren,
Thanks for this post. I have a question: How can I clear a mex file and make sure that it is removed from memory?
When I am developing a mex file (sfunction in Simulink), I want to test it in Simulink and then continue developing in MSVC but since the mex file which is a dll is loaded to memory, I cannot continue developing( cannot overwrite dll). I used clear(’all’) to remove it but sometimes it doesn’t remove it and there is no error or warning that it could not remove the mex file and why it cannot remove it. How can make sure that a dll is unloaded from Matlab?
Have good day.
Mansour-
Look at the help for clear. You’ll see an option for clearing mex-files that does clear them from memory.
–Loren
Quan-
Thanks. I enjoy your blog too.
–Loren
This is the quick loop I threw together. I’ll admit I am total MATLAB newbie (indenting seems to be lost):
%% Purposely leave behind “data” only
for f = who’ %’ This makes ‘f’ a 1×1 CELL not an ARRAY
if strcmpi(f,’data’), continue, end;
if strcmpi(f,’f'), continue, end;
clear (f{:});
end
clear f;
I’ve used keep.m:
http://www.mathworks.com/matlabcentral/fileexchange/loadFile.do?objectId=181
It works wonderfully.
clear theAir
keep onTrucking
Loren,
As expected since I’m not a fan of C & Unix, there is a lot about regular expressions that I don’t understand. So, I haven’t been able to confirm that anon’s suggestion is accurate. But, if it is, why didn’t The Mathworks just add that to the documentation of “clear” and avoid writing the new function “clearvar” with the -except option? After all, the “clear” function has the “function” keyword.
Regular expressions aren’t a C thing. They do appear in Linux/Unix, but not just there. They also appear in Microsoft Word and .NET, and date back to the 1950’s. Backus used them to describe Fortran, for example. You can do quite a bit in scientific computing without coming across them, of course, so it’s not a surprise that they can be unfamiliar to MATLAB veterans.
I have a related question … why is “pack” no longer allowed inside an m-file, but can only be typed at the command line? Does it conflict with the JIT, I suppose? I used to use “pack” a lot, inside an m-file, just before it tried to do something that was going to require a lot of memory.
Oliver-
I don’t know the reasons behind clearvar being separated from clear. I do know that users kept wanting to perform the operation however. I have to say that even if it were in the doc, for me, anon’s syntax wouldn’t stick with me and I’d write a wrapper M-file for it. Maybe that was the thinking?
–Loren
Loren,
You’re absolutely right in your thinking. Too many people found it too hard to keep the regular expressions straight, so clearvars was created as syntactic sugar to make this functionality easier. All clearvars does, is create a regular expression to perform the clear, and then call clear -regexp with that expression.
For example, say you have a set of variables like:
az1 = 1;
az2 = 2;
ay1 = 3;
ay2 = 4;
bz1 = 5;
bz2 = 6;
by1 = 7;
by2 = 8;
and you want to clear all of the variables that start with ‘a’ but not the ones that end with ‘2′. You could spend your time tinkering with the regular expression, or you could call:
clearvars a* -except *2
Which will in turn call:
clear -regexp ^(?!(.*2)$)(a.*)$
Which is a little messier.
-=>J
Tim-
Here’s the deal on pack. It never worked in functions but silently failed.
And here are the details. All pack does, literally, is run “save tempfile.mat; clear all; load tempfile.mat”. Given that, it cannot work inside a function, because it would save the function’s workspace, clear all (leaving any variables in the base workspace or running functions workspaces untouched), and then load the function’s variables back into the function’s workspace. All those variables in the other workspaces would leave memory pretty much as fragmented as it was to begin with. We simply added a warning a couple releases ago to let people know that it wouldn’t do anything.
–Loren
Tim,
Thanks for the bit of history regarding regular expressions.
Jason,
Thanks for the detail on how clearvars is implemented.
Loren,
As usual, thanks for the blog in general. I hope you can write something on uitable sometime soon. Many of us here are using it and are discovering its limitations.
That’s an interesting and disappointing piece of news to me about pack. I use it regularly in scripts in situations like Tim Davis describes, but I never noticed that it stopped working when I moved those scripts into functions. Is there a suggested way to get similar functionality within functions? Because sometimes pack is a real timesaver!
Jacob-
In a function, assuming you know the variable names, you can save, clear, reinitialize variable names with [] and then load again. You need to do ALL of these steps for MATLAB to be able to analyze the code and know which identifiers are variables and which are functions/methods/etc.
–Loren