7

I'd like to clear all variables from workspace, but with some exceptions defined by regular expressions.

The function clear has an additional option -regexp

clear -regexp expr1 ... exprN clears all variables that match any of the regular expressions listed. This option only clears variables.

So I'm looking for the opposite.

Also there is

clearvars -regexp p1 p2 ... clears all variables that match regular expression patterns p1, p2, and so on.

clearvars -except v1 v2 ... clears all variables except for those specified following the -except flag.

Which is already quite nice for complete variable names, but not working for regexp like the first option.

There are solutions on FEX, but I don't want to use additional custom functions.

But As there are such convenient solutions for the just slightly different cases above, I wonder if there is also a simple way to do:

keep -regexp expr1 ... exprN

with inbuilt functions.

Robert Seifert
  • 25,078
  • 11
  • 68
  • 113
  • `clearvars` supports regex for both matches and exclusions. See [this gist](https://gist.github.com/sco1/44ba551eecc942668c4c) – sco1 Jan 08 '16 at 14:15
  • Thanks for the hint! Though I don't know if that's a new feature, its inclusion in the doc certainly is. Otherwise the whole question would have been obsolete :) – Robert Seifert Jan 08 '16 at 16:20
  • To be honest it doesn't look very well documented in the current documentation either. Comparing the [R2013a doc](http://www.mathworks.com/help/releases/R2013a/matlab/ref/clearvars.html) with the [current doc](http://www.mathworks.com/help/matlab/ref/clearvars.html) they both only show the `-regexp` flag for either the variable scope *or* the exclusions, not for both. I'll probably submit an enhancement request. – sco1 Jan 08 '16 at 18:00
  • the current one has the line *Name Variables to Clear and Preserve Variables Using Regular Expressions* - quite clear. Does the old one contain that line? I don't have access to the old doc at home. But actually it doesn't really matter... ;) – Robert Seifert Jan 08 '16 at 18:08

1 Answers1

5

Take a look at this for inverse regexp matching. In this context:

clear -regexp ^((?!expr1|expr2|...).)*$

clearvars is not built-in, but an m-function, which has its own disadvantages. With the inverse regexp matching, you can do everything with clear (a built-in).

Community
  • 1
  • 1
Rody Oldenhuis
  • 37,726
  • 7
  • 50
  • 96