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
Loren,
So how does one clear “everything” (particularly variables and functions) except debugging breakpoints? Your “Debug Gotcha” is exactly that — it gets me every time I start a new project. I hate having to reset breakpoints when debugging, but I also prefer to restart with a clean slate using “clear all”.
Thanks,
Neill
Neill-
Use clear variables or clearvars with names, and then separately clear the functions you want to clear by name, e.g., clear foobar. Otherwise, you will clear all functions, including the one you are debugging, and it will lose it’s breakpoints.
–Loren
Neill, Loren
I use the following in some of my scripts to check if any breakpoints are set.
s = dbstatus;
if (isempty(s))
clear all
else
fprintf(‘\n\n Debug stop set\n Using “clear variables” instead of “clear all”\n\n’);
clear variables
end
Not a perfect solution but at least I can debug, and start with no defined variables.
Robert-
Nice suggestion.
–Loren
Concerning the debug gotcha. I have been annoyed by this for years. Could you please request that the developers provide an option for example clear -exceptbreak, to at least be able to selectively turn this feature off. Even better, since I rarely want break points cleared out when issuing the clear command, it would be great if I could set the default behavior in my preferences to leave break points. Note if I want to clear out all break points I can do this within the debugger
Jon-
I will put the request in and you can too:
http://www.mathworks.com/support/service_requests/contact_support.do
–Loren
I don’t quite see what Neill & Robert are trying to do. If I want a ‘clean slate’, I write a function, unless I also need to recover memory. The variables created in the function can even be returned.
function S = foo
% Perform calculations, etc.
% Remove loop control variables and other clutter,
% perhaps with clearvars -except.
save fooTemp.mat;
S = load(‘fooTemp.mat’);
delete fooTemp.mat;
% There might be a clean way to do this in core memory,
% but the only way I know involves repeated eval calls.
return;
Loren,
in Solaris environment (and I suspect in Linux too), in batch execution the statement clear does not work. Is there a turnaround to free memory in Unix from a matlab script?
regards
Vittorio-
What exactly do you mean about using clear in batch and it not working?
clear should clear the memory from MATLAB, enabling MATLAB to use that memory again, if required. I believe the memory does not get returned to the operating system until you quit MATLAB because of how the underlying memory managers work. It behaves differently on Windows.
–Loren
Jorgen, Loren,
I have tried using Jorgen’s approach, but this approach has also frustrated me because I can’t do it in core memory. You have to save variables to a file and then back in the root workspace reload them. This isn’t reasonable if the variables take much memory. Besides, I don’t like having to type “load foo” every time. And I don’t like creating unnecessary .mat files. Isn’t there any way to simply set the variables from a function directly into Matlab’s root workspace?
Thanks, John
John-
There are at least 2 ways to get the data to the base workspace besides the load/save method. First, and highly encouraged, is to return the variables as outputs from the function. Second possibility, which I prefer less, is to have your function issue some assignin statements to the base workspace and get your function variables to POOF (as Steve Lord says) the data into the base workspace.
–Loren
Hi,
If i don’t want a variable getting cleared(deleted) from the workspace, but still it can be updated. Can this be done? …some sort of locking of the variable.
-Sunny
Sunny,
Check out persistent ( http://www.mathworks.com/help/techdoc/ref/persistent.html ) if the variable you want to save is part of a function workspace.
–Loren
I was wondering if clear could be used with a matlab array. By that I mean I would like to call a command like this
varstoclear=[v1,a4,a6]
clear varstoclear
Here v1, a4,a6 are well defined variables. Is it possible to do something like this? I want to do this because I have a whole set of variables that I would want to clear. So instead of giving clear followed by a huge list of arguements, I feel it is cleaner if all the variables to be cleared are kept in an array, and clear is called on this array.
Ravi-
If you look at the documentation, you will see that you can clear individual variables. But if you want to clear them, you must do so by name. So this would work for your example.
varstoclear = {'v1','a4','a6'}; notice curly braces clear(varstoclear{:})That places the names into a cell array, calls clear in functional form by using the comma-separated list feature of cell arrays. You can learn more about those topics on other posts here and in the user documentation.
–Loren