Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can one clear all the variables but the ones wanted [duplicate]

Tags:

matlab

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?

like image 685
Ander Biguri Avatar asked Jan 08 '16 12:01

Ander Biguri


2 Answers

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.

like image 157
sco1 Avatar answered Nov 10 '22 03:11

sco1


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');
like image 26