In each case, regular expressions can be used to operate on all variables except for a short list.
You can use LOAD with the -REGEXP option to specify a regular expression. Suppose 'mydata.mat' contains the following variables:
The following code illustrates several examples:
load mydata -regexp ^(?!var$).
load mydata -regexp ^(?!a$|b$).
load mydata -regexp ^(?!myvar1$|myvar_abc$|data$).
This idea can be extended to clear all variables from MATLAB's workspace except for a few you do not want to clear. For example, if we have the following variables stored in the workspace:
The = 1;
seed = 2;
of = 3;
the = 4;
tree = 5;
seeds = 25;
aseed = 15;
We can clear all variables except the one named 'seed' by executing the following command:
clear -regexp ^(?!seed$).
Alternatively, we can use the following syntax to clear all variables except for 'seed', 'of', and 'the':
clear -regexp ^(?!seed$|of$|the$).
As of MATLAB 7.6 (R2008a), you can use CLEARVARS with the "-except" flag. For example, the expression
will remove every variable from your workspace except the variables "A" and "B".
You may also use the MATLAB Central file called "keep.m" which provides similar functionality:
Note that MathWorks does not guarantee or warrant the use or content of these submissions. Any questions, issues, or complaints should be directed to the contributing author.