Graphics    

Example -- Using Function Handles in a GUI

This example shows how to create a simple GUI that plots variables that exist in the base workspace. It is defined in a single M-file that contains both the layout commands and the callbacks. This example uses function handles to specify callback functions. See Function Handle Callbacks for more information on the use of function handle callbacks.

Click this link to display the example code in the MATLAB editor.

Here is what the GUI looks like.

The GUI Layout

The first step is to define each component in the GUI and save the handles.

Initialize the GUI

The list box and the hold toggle button need to be initialized before the GUI is ready to use, which is accomplished by executing their callbacks. Note that you must specify all the arguments when calling these functions since we are not evaluating function handles here.

The Callback Functions

Only the list box, toggle button, and plot push button have callbacks.

List Box Callback.   The list box callback takes advantage of the callback object handle (first argument) generated by MATLAB to set the String property to the current list of workspace variables.

Note that for simplicity, the contents of the list box is updated every time the user selects an item. A separate update button would be a more robust approach.

Toggle Button Callback.   The toggle button callback requires two additional arguments -- the handles of the GUI figure and axes. We can use the handles saved when we created the figure and axes (h_figure and h_axes) because function handle callbacks will execute within the context of this M-file.

We want the GUI to call the hold command, but hold operates only on the current figure. Our GUI figure cannot become the current figure because we've hidden its handle. To implement the functionality of hold, this callback sets the axes NextPlot property directly.

Plot Button Callback.   The plot button callback performs three tasks:

Using the GUI

Select some variables from the workspace and overlay stem and bar plots.


  Why Use Function Handle Callbacks Figure Properties