Today I want to talk a little bit about defensive programming for GUIs (graphical user interfaces) and other programs with graphics callbacks.
Contents
What Can Go Wrong
First, why is this worthy of a blog at all? Well, supposed the following. Someone, who shall remain nameless, has created a GUI to do a very useful task. However, the interactions are programmed to work on the current figure or current axes. Now, a user of this GUI, who shall also remain nameless, is a very impatient person and, while waiting for the GUI to respond, starts working in another figure window. When this user goes back to the GUI and tries to accomplish the next task, strange behaviors and errors emerge. What's gone wrong? Most likely, the GUI callbacks, which implement the behavior of the GUI, probably are programmed using a poor technique.
Don't Depend on gca, gcf
One technique that can easily misfire is referring to some entity that has global state, such as gcf or gca, referring to the current figure or axes. The problem arises when a GUI user interrupts the interaction in a GUI with interaction in another figure window. By the time the user returns to the initial GUI, either or both of gcf or gca may no longer refer to the objects intended by the GUI author. What should the GUI programmer do instead? There are several acceptable choices available.
Use gcbo
One possibility is to have the callback refer to gcbo, the handle of the object from which the callback is executed. From there, you can find other objects needed to complete the interaction.
Use Handles
An even better choice is store handles to the objects you want to the GUI to operate on, either in the workspace available to a nested function, or in a structure tucked inside the GUI, perhaps in application data, accessed through getappdata and the corresponding set method.
Reference Material
Here are some references in the MATLAB documentation to help you with programming a GUI.
Avoid Global State
Global state is fragile and can be easy to disrupt. To avoid using global state, use techniques like the ones in this blog, the recent one on using the MException object, or use nested functions, among other possibilities.
Your Thoughts?
Will these ideas help you with your programs? Post here with your thoughts.
Get
the MATLAB code
Published with MATLAB® 7.5

Loren,
I am interested in your thoughts on the seeming conflict between nested functions and the value associated with writing routines which are re-usable in many different fashions. Since nested functions, by definition can’t be called from anyplace else, they are the ultimate in “one of” code. They are even likely to be harder to transport since they can depend on specific variables being defined by specific names in the calling function. What are your thoughts on this?
Thanks,
Dan
Dan-
Not at all! They are totally reusable since they carry their workspace. You can have several GUIs all with function handles to the same nested function, but separate workspaces. Look at this blog article for a good example.
–Loren
Hi Loren,
A somewhat unrelated graphics question - what is the quickest way to visualize a 2D mesh (such as used for FEM) of quads, containing, say, 150000 odd edges indexing into 80000 odd vertices in MATLAB? I’ve tried the following methods and they all fail ->
(1) Meshsurf and then mesh - not enough memory (obviously)
(2) ‘Line’ commands to generate each individual edge - extremely slow; draws and subsequent redraws take minutes.
(3) A single ‘line’ object is fast but it generates a plot with extra lines, because the ‘line’ command can’t create disjointed ‘line’ objects.
Is there anyway I can do this in MATLAB at all without resorting to external graphics (via MEX)? Is there anyway ‘line’ (or an equivalent command) can create disjointed objects?
Thank you,
Narayan
Narayan-
I vowed to myself early on that since this was a blog about language, I would not answer questions about graphics to a large extent. Please use the newsgroup, or contact technical support for graphics issues. Thanks.
–Loren
For the handles section I’d like to add the following comment: just myself “learned” again through some error, that it is good practice ALWAYS to use the handle of the axes stored e.g. in the guidata, so plot(handles.axes1, …) or xlabel(handles.axes1, …) or grid(handles.axes1, ‘on’)
I recently created a small GUI in Matlab and looked to some of the Matlab demos for guidance (e.g., lorenz.m, truss.m). I ran into some trouble copying them precisely due to issues you discussed here. Any chance these might be updated to reflect best practices?
Thanks for the interesting blog topics!
Patrick.
Patrick-
I am not sure of the plans for updating those demos but I’ve put your request in the system. Thanks for bringing it to my attention.
–Loren
Narayan-
I will comment on 3) in your question. You CAN make a line that is in separate segments by placing a NaN value between separate pieces. E.g.,
produces a line in 2 pieces.
–Loren
Hi Loren,
Thank you so much for that - I understand you receive a large volume of correspondence / comments and really appreciate your help.
Sincerely,
Narayan
I agree that using Handles is the way to go to make it monkey proof, yet obtaining a handle upfront, before drawing is done might seem tricky. e.g. when you want to use the refreshdata cmd somewhere in the future.
Maybe I have overlooked a direct command for this, otherwise an easy way to ask for a Handle for a graphics series object such as lineseries, without drawing first might be
PlotHandle=plot(NaN,NaN,……’XDataSource,’xdata1′,…
Mind you that xdata1 only takes full vectors, no matrices and does not eat indexing, which makes it a bit Matlab unlike.
Also may be good to know that NaN generally suppresses graphics output and can be used in X and Y plotvectors to suppress the drawing of that respective line segment.
Jaap-
You might look into the function findobj. I don’t believe it should be a burden to capture handles as you create objects in an M-file — interactively it is more understandable.
–Loren
Loren,
Thanks for your blog and reply.
Findobj is good to retrieve the handle, but how can I create a graphics handle without drawing -yet-, such as when setting up for ‘refreshdata’ in a later stage because I do not have the data yet? I want to keep my graphics outside my application because it is targeted to an embedded platform. A single line with refreshdata is all that is needed to get graphics going during development and debugging.
NaN as mentioned before in
PlotHandle=plot(NaN,NaN,……’XDataSource,’xdata1′,…
might be helpful and does the trick but when talking Matlab language it is not dying in elegance. The same applies for the ‘XDataSource’ which does not behave Matlab like by only consuming pure vectors, no matrices and no indexing.
btw:findobj returns an error if a handle refers to
a nonexistent graphics object.
Jaap
Jaap-
Will setting the figure visibility to off work for you?
–Loren
Loren,
There are a few ways around it, e.g. like I mentioned before using NaN. Yet to stay true to the forum, being about the Matlab language I am merely pointing out some odd behaviour in the language namely
1) getting a graphics handle without drawing directly needs a workaround.
2) the XDataSource (and Y,Z) does not allow other than full vectors, no matrices, no indexing. Quite Matlab unlike.
Of course there is a workaround for the above as there is for other Matlab peculiarities.
Jaap-
For now, here’s one more idea for you to try. Put your data for later plotting into a struct.
linestruct.XData = myxdata;
linestruct.YData = myydata;
…
And later on do this just after establishing a linehandle.
set(linehandle,linestruct)
–Loren
Great Tips, especially the gcbo one. I haven’t run into the errors you mentioned in the article, but I can clearly see that its entirely possible! I’ll start implementing this in my GUIs from now on.
Loren,
i am working on a gui which has an axes and a push button.
I have set the busyaction property to “queue” for the push button and interruptible property for the figure on which it sits to “on”. i update the position of a point C on the plot in a sequence to show motion of that point in the axes. when i hit pause, i want this updating of the axes to also pause… however, i have to hit pause more than once usually to get it to respond. can you please suggest some remedies?
i do uiwait on the main figure handle… however, the pushbutton callback itself does not get called… thats the issue.
thanks,
nive
thanks for your reply email Loren. I have here (I hope) a relevant question: are callbacks written as nested fucntions 1) safer? 2) faster? than a callback defined as a stand alone function?
Nive-
Nested function callbacks are definitely safer, speed depends deeply on the application details, but performance shouldn’t usually be radically different.
–Loren
I’ve written a GUI to help me plot data in certain data structures. I set it up so it can generate a lot of plots at once. However, I also want to be able to click a “hold” check box that simply turns hold on to allow people to plot other things on top of the current figure. The problem is, when I click on the figure I want to add to and then go back to the GUI to select what to plot gcf always comes up with the handle to the GUI not the handle to the figure I just clicked on. Is there a way to get the handle to the second most recent figure?
Brendon-
Without being positive about the details, I am SURE you don’t want to use gcf. Perhaps gcbf would be better (gets the callback figure).
–Loren
GCBO still returns the GUI’s handle because it’s the GUI’s plot button whose callback is executing. I need the handle to the figure I want that plotting function to plot on top of. I really want it to be as simple as clicking on the plot you want to plot on top of and then going back to the data and checking what you want plotted and hitting the plot button. I just can’t get that handle to the figure that was clicked on to send to the GUI’s plot button callback…
Brendon-
What I am going to tell you next is risky and not bullet-proof but might work. get(0, ‘children’). Assuming you only get figures back, or you filter for them, you can then get the 2nd one on the list. Risky because someone could click again on another figure before the callback is called.
–Loren
Thanks, that helps. I read your article and I understand why it’s risky but it’s an engineering tool only and thus doesn’t need to be invulnerable to impatience. People are expected to know what’s up.
Another possibility is to have the GUI create a UICONTROL, UIPUSHTOOL, or UITOGGLETOOL on the figures it creates and have that object use GCBF to adjust the hold state for the figure in which it’s located. Alternately, UIMENU or UICONTEXTMENU could also do the trick.
http://www.mathworks.com/access/helpdesk/help/techdoc/ref/uicontrol.html
http://www.mathworks.com/access/helpdesk/help/techdoc/ref/uipushtool.html
http://www.mathworks.com/access/helpdesk/help/techdoc/ref/uitoggletool.html
http://www.mathworks.com/access/helpdesk/help/techdoc/ref/uimenu.html
http://www.mathworks.com/access/helpdesk/help/techdoc/ref/uicontextmenu.html
Hello Loren,
Recently I had created a GUI which uses a JAVA object (JPanel) to create a custom table,during the process I found that the sequence of execution is not what was expected.The callbacks associated to the Java Objects were fired after the completion of the Matlab calls. The problem became more complex when I had called a seperate Matlab GUI and then set the focus back on the GUI with the Java Object,this time the sequence of execution was the same as expected.
I feel that the Stack order could be a possible reason.
Kindly help me understand.
Jegan-
This problem is too complex to do in this forum, especially without code. Please contact technical support for help here and be sure to have your code ready to send them.
–Loren