ce3600bebbf2c067fd1713755acb71a318710589.svn-base 2.67 KB
%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