Often when running long memory expensive programs I want to clear everything but some specific variables. If one wants to delete just some variables clear varA varB
can be used, but what about deleting all but this specific variables?
Asked
Active
Viewed 1.0k times
11

Ander Biguri
- 35,140
- 11
- 74
- 120
-
5While `clear` does allow for a regex pattern matching, [`clearvars`](http://www.mathworks.com/help/matlab/ref/clearvars.html) is probably more relevant, particularly the third syntax. – sco1 Jan 08 '16 at 12:05
-
@excaza Wow didnt know about that one! post an answer! – Ander Biguri Jan 08 '16 at 12:07
-
Instead clear your vars whenever you are finished with them. It is a must in Matlab as it doesn't understand functional chains with multiple arguments. – percusse Jan 08 '16 at 13:22
-
@percusse yeah but sometimes I do a level set with 50 cosntarins in aloop, and I want to delete all but the result, as lots of them are mid variables. – Ander Biguri Jan 08 '16 at 13:26
-
@AnderBiguri I hear you loud and clear. Those stuff I tend to push inside a cell and delete the cell afterwards. Mid vars are really super annoying. – percusse Jan 08 '16 at 13:31
2 Answers
21
As mentioned above, clearvars
includes a syntax for keeping variables in the workspace while clearing the remainder:
a = 1; b = 1; c = 1; d = 1;
keepvars = {'c', 'd'};
clearvars('-except', keepvars{:});
Which functions as expected.
Like clear
, it can also accommodate regexp
matching:
a1 = 1; a2 = 1; b = 1; c = 1;
keepvars = 'a\d'; % regex pattern
clearvars('-except', '-regexp', keepvars);
Which retains a1
and a2
, as expected.

sco1
- 12,154
- 5
- 26
- 48
10
Make use of the fact that both who
and whos
have return values that can be stored in variables. The former returns a cell array of strings, the latter a struct array. For what you need, the former will suffice:
%// don't delete these '
keepvars = {'varA','varB'};
%// delete these
delvars = setdiff(who,keepvars);
clear(delvars{:},'delvars');

rayryeng
- 102,964
- 22
- 184
- 193

Andras Deak -- Слава Україні
- 33,737
- 11
- 83
- 111