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.
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.
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.
To leave a comment, please click here to sign in to your MathWorks Account or create a new one.