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?
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.
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');
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With