How to keep the same figure in callbacks

A very common thing to within a GUI is to create a new figure on which you plot a graph.

Now, often, you also want to always plot on the same figure and keep track of what is going where. A simple solution is to give unique number to each figure like :

figure(100);

But if you start making more and more GUIs and subfunctions, this solution becomes quickly a nightmare. I propose a much simpler solution that will just get you rid of this issue.

Let’s assume you have a callback that need to create a figure. Now instead of figure(100) Use the following code :

if ~isfield(handles,'hPlotFrame') || isempty(handles.hPlotFrame) || ~ishandle(handles.hPlotFrame)
      handles.hPlotFrame=figure;
      guidata(handles.output,handles);
else
      figure(handles.hPlotFrame);
end

Ok, this code does seem a little complicated but it is quite reliable. What it does is simple. It checks the handles structure (the one that come with all GUIs made with the GUIDE) for the presence of hPlotFrame. hPlotFrame stores the handle to your figure. If your figure has been deleted or never existed, it creates it and store the handle to the figure in handles. If the figure already exists, it raises it and you plot over the same figure. This IF is just to be on the safe side if anything happen that is unexpected in your program. If you are curious about this || operator, have a look at my post on AND AND.

Storing your figure handle in handles is also advantageous because  you can close you figure when you GUI ends. Matlab cleans memory for you when you function are finished but it does not clean your desktop of windows.

This entry was posted in Intermediate, Making interfaces. Bookmark the permalink.

Leave a Reply

Your email address will not be published. Required fields are marked *