Clearing Global variables... except for.

17 vues (au cours des 30 derniers jours)
Trevor Harris
Trevor Harris le 11 Oct 2012
Hey all,
I wish to clear all my global variables apart from two. So I've generated a cell array of strings that contain all my global variables and removed the two I wish to save:
globals = who('global');
globals = globals(~strcmpi(globals,'waitGUI'));
globals = globals(~strcmpi(globals,'decayFig'));
This is where I'm stuck. How do I clear all the variables who's names of the variables are strings within the cell array "globals"? Thanks!
Trevor

Réponses (4)

Daniel Shub
Daniel Shub le 11 Oct 2012
Modifié(e) : Daniel Shub le 11 Oct 2012
To remove the variables locally
clear(globals{:})
to remove them globally
clear('global', var{:})
You should also look into the regexp support of clear and the -except flag.
clear -global -except waitGUI decayFig
  2 commentaires
Trevor Harris
Trevor Harris le 11 Oct 2012
I tried that, it didn't work. This is from my command line:
K>> globals = who('global')
globals =
'SaveData'
'crossPlot'
'dataPan'
'decayFig'
'dpDecay'
'dpXUnfiltered'
'fitLine'
'fitType'
'fitTypeString'
'hAxes'
'll'
'll2'
'll3'
'peaksPlot'
'peridYLabel'
'periodAxPlot'
'pfit'
'ssFFT'
'ssTT'
'timeTraceUnfiltPlot'
'troughsPlot'
'waitGUI'
'xunitBase'
'yunitIs'
K>> clear(globals{:})
K>> who('global');
Your variables are:
SaveData dpXUnfiltered ll periodAxPlot troughsPlot crossPlot fitLine ll2 pfit waitGUI dataPan fitType ll3 ssFFT xunitBase decayFig fitTypeString peaksPlot ssTT yunitIs dpDecay hAxes peridYLabel timeTraceUnfiltPlot
Daniel Shub
Daniel Shub le 11 Oct 2012
Sorry I thought you wanted to do it locally. To do it globally is essentially the same, except you need the global flag. You really should read the documentation of clear, since there are a number of better ways of doing this.

Connectez-vous pour commenter.


José-Luis
José-Luis le 11 Oct 2012
Modifié(e) : José-Luis le 11 Oct 2012

Image Analyst
Image Analyst le 11 Oct 2012
Here's one way. Just save what you want into local variables, then destroy all globals, then recreate the globals you want:
% Save into local variables.
saved_waitGUI = waitGUI;
saved_decayFig = decayFig;
% Clear all globals
clear global;
% Redeclare globals
global waitGUI;
global decayFig;
% Restore the globals we wanted to keep
waitGUI = keep_waitGUI;
decayFig = keep_decayFig;

Jan
Jan le 11 Oct 2012
A meta-answer: Avoid working with GLOBALS. There are always better solutions which do not make the debugging a trip to hell.

Catégories

En savoir plus sur Develop Apps Using App Designer dans Help Center et File Exchange

Community Treasure Hunt

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

Start Hunting!

Translated by