Loren on the Art of MATLAB

April 8th, 2008

Clearing the Air

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

27 Responses to “Clearing the Air”

  1. anon replied on :

    I use frequently

    clear -regexp ^(?!variable$).

    which removes all variables except for the variable I have named there.

  2. Cris Luengo replied on :

    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.

  3. Quan replied on :

    Nice post Loren. I’m sure this will come in handy for me

  4. mansour replied on :

    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.

  5. Loren replied on :

    Mansour-

    Look at the help for clear. You’ll see an option for clearing mex-files that does clear them from memory.

    –Loren

  6. Loren replied on :

    Quan-

    Thanks. I enjoy your blog too.

    –Loren

  7. RevRagnarok replied on :

    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;

  8. Ben replied on :

    I’ve used keep.m:
    http://www.mathworks.com/matlabcentral/fileexchange/loadFile.do?objectId=181
    It works wonderfully.

    clear theAir
    keep onTrucking

  9. Oliver A. Chapman, P.E. replied on :

    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.

  10. Tim Davis replied on :

    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.

  11. Loren replied on :

    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

  12. Jason Breslau replied on :

    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

  13. Loren replied on :

    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

  14. Oliver A. Chapman, P.E. replied on :

    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.

  15. Jacob replied on :

    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!

  16. Loren replied on :

    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

  17. Neill Smith replied on :

    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

  18. Loren replied on :

    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

  19. Robert Adams replied on :

    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.

  20. Loren replied on :

    Robert-

    Nice suggestion.

    –Loren

  21. jon replied on :

    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

  22. Loren replied on :

    Jon-

    I will put the request in and you can too:

    http://www.mathworks.com/support/service_requests/contact_support.do

    –Loren

  23. Jorgen Harmse replied on :

    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;

  24. Vittorio replied on :

    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

  25. Loren replied on :

    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

  26. John replied on :

    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

  27. Loren replied on :

    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

Leave a Reply

Wrap code fragments inside <pre> tags, like this:

<pre class="code">
a = magic(3);
sum(a)
</pre>

If you have a "<" character in your code, either follow it with a space or replace it with "&lt;" (including the semicolon).


Loren Shure works on design of the MATLAB language at The MathWorks. She writes here about once a week on MATLAB programming and related topics.

  • Jun: I totally can not believe it, Loren. You are really helpful. Thank you so much, MATLAB master!
  • Loren: Wow folks- Always lots of interest when there’s a quickie to try out! I will only make 2 general...
  • Loren: Jun- ismember is your friend here: >> [aa,ind] = ismember(Array2,Arra y1) aa = 1 1 1 1 1 1 1 ind = 1 2 1 4 4 3...
  • Dan: I like the first way better than the second way. Combining the arrays into one and running any is nice, although...
  • James Myatt: How about I = (a == 0 | b == 0); a(I) = []; b(I) = [];
  • Tunc: Hello Loren, love your blog because of such inspiring and challenging comments to such ’small’...
  • Pekka Kumpulainen: Here is my tradeoff. I usually want to keep the original variables as they are most probably...
  • Iain: Followup: Of course, to allow NaNs (counting them as non-zero): mask = (a~=0) & (b~=0); The mask says “a...
  • Matt Fig: I would usually go with something like this: y = a&b; x = a(y); y = b(y); But I was surprised to find...
  • kk: c=all([a;b]) a(c) a(b)

These postings are the author's and don't necessarily represent the opinions of The MathWorks.