Skip to Main Content Skip to Search
File Exchange
MATLAB Newsgroup
Link Exchange
  Blogs  
 Contest 
MathWorks.com

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

16 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

Leave a Reply


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.

  • Brad Phelan: Hi Tim, I understand where you are coming from. It is my one pet annoyance with Matlab, the lack of...
  • Loren: Timothee- Anonymous functions can only be a single (complicated) expression. You might be able to do what you...
  • Timothee: Is there a way to combine multiple commands in anonymous functions? ex1: fun=@(A)([V,D]=eig(A ); A*V-V*D)...
  • Loren: Here’s Cleve’s reply to Etienne: The crucial factor is the number and location of the nonzero...
  • Loren: Tristan- Nested functions can be slower in some cases currently. We know we have some opportunities to...
  • Tristan: Wow! I just tried with a global variable and it’s 5 times slower than with a argument! function...
  • Jon: Loren, I encountered this same problem and I attempted to find the answer by looking at the documentation for...
  • Tristan: “One thing that I have long wondered about is relative speed of nested functions relative to...
  • Etienne Non: Hi! I’m trying to understand why the Matlab function LU.m takes almost 20 times more time to...
  • Loren: Jonathan- The behavior you see is because the variable x has to come into inplaceTest and then a copy is made...

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

Related Topics