1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
%Program clearnot. This program is not a function!
%
%This program will clear all the variables in the workspace except for those
%with names specified in 'varname'. The variable 'varname' can either be a
%string with one name or a cell array of strings with multiple names.
%
%
%Example 1:
%Assume a variable exists in the workspace called 'myVariable'. To clear
%the worksace of everything but 'myVariable', type the following commands:
%
%varname = 'myVariable';
%clearnot
%
%
%Example 2:
%To keep multiple variables, save the names to a cell array.
%
%varname = {'myVariable1','myVariable2','myVariable3'};
%clearnot
%
%
%Brett Shapiro
%16 June 2008
%
%Notes: I did not make this program a function because functions have their
%own workspace. It is not clear to me if there is a way to remove a
%variable in one workspace using that of another.
if exist('varname','var')
% Ensuring that variables used in this program are not added to the list
% of variabled in the workspace.
clear ii
clear jj
clear flag
clear varlistlength
clear varlist
% Making sure that varname is a cell array
if iscell(varname) == 0 && ischar(varname) == 1
dummy{1} = varname;
varname = dummy;
clear dummy
end
varlist = who;
varlistlength = length(varlist);
varnamelength = length(varname);
% Searching for entered names that do not exist
for jj = 1:varnamelength
if sum(strcmp(varlist,varname{jj})) == 0
warning(['variable name ''',varname{jj},''' does not exist in the workspace.']) %#ok<WNTAG>
end
end
% Removing variables from workspace
for ii = 1:varlistlength
% If flag > 0, nothing is cleared because it is either the desired
% variable or one used in this program.
flag = strcmp(varlist{ii},'varname') + strcmp(varlist{ii},'varnamelength')+ strcmp(varlist{ii},'varlist') + strcmp(varlist{ii},'varlength') + strcmp(varlist{ii},'flag');
for jj = 1:varnamelength
flag = flag + strcmp(varlist{ii},varname{jj});
end
if flag == 0;
eval(['clear ',varlist{ii}])
end
end
% Removing variables used in this program
clear varlist
clear varlistlength
clear varname
clear varlength
clear varnamelength
clear flag
clear ii
clear jj
else % varname does not exist
error('Matlab:undefinded_variable','Variable ''varname'' undefined.\nLoad the name of the variable to remain in the workspace into ''varname'' before running this program.\nFor more information type ''help clearnot''.')
end