How do I load all variables from a MATLAB file except a few specific variables?

48 次查看(过去 30 天)
When using LOAD, I would like to load all the variables present in the MATLAB file, except for a few specific ones which I do not want to load. Also, when using CLEAR, I would like to be able to clear all variables in the workspace except a few, specific ones which I want to keep.

采纳的回答

MathWorks Support Team
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:
myvar1
variable2
var
a
b
abcd
myvar_abc
data
The following code illustrates several examples:
%%Load all variables except 'var'
load mydata -regexp ^(?!var$).
%%Load all variables except 'a' and 'b'
load mydata -regexp ^(?!a$|b$).
%%Load all variables except 'myvar1', 'myvar_abc', and 'data'
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
clearvars -except A B
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:
<http://www.mathworks.com/matlabcentral/fileexchange/loadFile.do?objectId=181>
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.

更多回答(0 个)

类别

Help CenterFile Exchange 中查找有关 Whos 的更多信息

产品

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!

Translated by