Loren on the Art of MATLAB

Turn ideas into MATLAB

Note

Loren on the Art of MATLAB has been archived and will not be updated.

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.




Published with MATLAB® 7.6


  • print

댓글

댓글을 남기려면 링크 를 클릭하여 MathWorks 계정에 로그인하거나 계정을 새로 만드십시오.