How can I close an old figure when a new figure is plotted?

12 views (last 30 days)
In my code I have a slider that is moved by the user. Each time it moves, it updates a value used for a calculation, which is plotted in a new figure. Thereby, each time the slider is moved, a new figure opens. I end up having a large number of figures, so I would like to close the old figure when the new one is created.
Any help is appreciated.

Answers (2)

Steven Lord
Steven Lord on 28 Jul 2015
Why not just have the slider callback update the graphics in a figure opened for that purpose when your GUI was initialized? Why create a whole new figure?
  2 Comments
KirbyG_
KirbyG_ on 28 Jul 2015
Edited: KirbyG_ on 28 Jul 2015
I have one plot in my GUI, and a subplot (2 by 1) in the figure window. I would put the subplot in the GUI as well but I dont know how to do this while ensuring my code works.

Sign in to comment.


Image Analyst
Image Analyst on 29 Jul 2015
In the slider callback I think you can just have
global hFigure; % Get handle to existing figure.
try
close(hFigure); % Close it
catch
% Get here if figure doesn't exist, but just ignore the error.
end
hFigure = figure;
plot(.................
Or maybe you can use exist instead of try/catch
if exist('hFigure', 'var') % See if global variable exists yet.
close(hFigure); % Close it
end
global hFigure; % Instantiate new global variable.
hFigure = figure;
plot(.................
There are other ways (more complicated I think) so let us know if neither of those works.

Community Treasure Hunt

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

Start Hunting!