| Products & Services | Solutions | Academia | Support | User Community | Company |
| Download Product Updates | | | Get Pricing | | | Trial Software |
| Documentation → MATLAB |
| Contents | Index |
| Learn more about MATLAB |
| On this page… |
|---|
Handle Graphics objects have many properties for which you can define callback functions. When a specific event occurs (e.g., you click a push button or delete a figure), the corresponding callback function executes. You can specify the value of a callback property as a
String that is a MATLAB command or the name of an M-file
Cell array of strings
Function handle or a cell array containing a function handle and additional arguments
The following sections illustrate how to define function handle callbacks for Handle Graphics objects.
Introduction describes how to define a function handle callback.
Why Use Function Handle Callbacks provides information on the advantages of using function handle callbacks.
Example — Using Function Handles in GUIs shows how to create a simple GUI that uses function handle callbacks.
For general information on function handles, see the function handle reference page.
In Handle Graphics technology, functions that you want to use as function handle callbacks must define at least two input arguments in the function definition:
The handle of the object generating the callback (the source of the event)
The event data structure (can be empty for some callbacks)
MATLAB passes these two arguments implicitly whenever the callback executes. For example, consider the following statements, which are in a single M-file.
function myGui % Create a figure and specify a callback figure('WindowButtonDownFcn',@myCallback) . . . % Callback subfunction defines two input arguments function myCallback(src,eventdata) . . .
The first statement creates a figure and assigns a function handle to its WindowButtondownFcn property (created by using the @ symbol before the function name). This function handle points to the subfunction myCallback. The definition of myCallback must specify the two required input arguments in its function definition line.
You can define the callback function to accept additional input arguments by adding them to the function definition:
function myCallback(src,eventdata,arg1,arg2)
When using additional arguments for the callback function, you must set the value of the property to a cell array (i.e., enclose the function handle and arguments in curly braces):
figure('WindowButtonDownFcn',{@myCallback,arg1,arg2})Defining a callback as a cell array of strings is a special case because MATLAB treats it differently from a simple string. Setting a callback property to a string causes MATLAB to evaluate that string in the base workspace when the callback is invoked. However, setting a callback to a cell array of strings requires the following:
The cell array must contain the name of an M-file that is on the MATLAB path as the first string element.
The M-file callback must define at least two arguments (the handle of the callback object and an empty matrix).
Any additional strings in the cell array are passed to the M-file callback as arguments.
For example,
figure('WindowButtonDownFcn',{myCallback,arg1})requires you to define a function M-file that uses three arguments:
function myCallback(src,eventdata,arg1)
Using function handles to specify callbacks provides some advantages over the use of strings, which must be either MATLAB commands or the name of an M-file that will be on the MATLAB path at run time.
Function handles let you use a single M-file for all callbacks. This functionality is useful when you are creating graphical user interfaces, because you can include both the layout commands and callbacks in one file.
For information on how to access subfunctions, see Calling Subfunctions.
When MATLAB evaluates function handles, the same variables are in scope as when the function handle was created. (In contrast, callbacks specified as strings are evaluated in the base workspace.) This simplifies the process of managing global data, such as object handles, in a GUI.
For example, suppose you create a GUI with a list box that displays workspace variables and a push button whose callback creates a plot using the variables selected in the list box. The push button callback needs the handle of the list box to query the names of the selected variables. Here's what to do:
Create the list box and save the handle:
h_listbox = uicontrol('Style','listbox',... etc.);Pass the list box handle to the push button's callback, which is defined in the same M-file:
h_plot_button = uicontrol('Style','pushbutton',...
'Callback',{@plot_button_callback,h_listbox},...,etc.);The handle of the list box is now available in the plot button's callback without relying on global variables or using findobj to search for the handle. See Example — Using Function Handles in GUIs for an example that uses this technique.
MATLAB passes additional information to the callback when it executes. This information includes the handle of the callback object (the source of the callback event) and event data that is specific to the particular callback property.
For example, the event data returned for the figure KeyPressFcn property is a structure that contains information about which keys were pressed.
Information about the event data associated with any given callback property is included with the property's documentation. Use the Handle Graphics Property Browser to access property documentation.
A function handle can point to a function that is not in scope at the time of execution. For example, the function can be a subfunction in another M-file.
For a general discussion of function handles, see the Function Handles and Anonymous Functions in the MATLAB documentation.
This example creates a simple GUI that plots workspace variables. 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. Callbacks are implemented as nested functions to reduce the need to pass variables as arguments.
The documentation for this example does not list all the code used to lay out and program the GUI. To see a complete code listing, use the links in the Note.
Note If you are using the MATLAB Help browser, run this example or open it in the MATLAB editor. |
See Function Handle Callbacks for more information on the use of function handle callbacks.
The following graphic shows the GUI after running the example code. The program creates two variables (testvarX and testVarY) in the base workspace for testing purposes.

The GUI layout is split among three uipanel containers. The left-hand panel contains the axes, the right-hand panel contains a list box to display workspace variables, and the bottom panel contains the plot and hold buttons and the plot type pop-up menu.
The list box and the hold toggle button need to be initialized before the GUI is ready to use. This is accomplished by executing their callbacks. Because you are calling these functions directly, MATLAB does not implicitly pass the first two arguments, as it would if these functions were executed as callbacks in response to an event. Therefore you must explicitly pass all arguments in these function calls:
% Initialize list box and make sure % the hold toggle is set correctly listBoxCallback(listBox,[]) holdToggleCallback(holdToggle,[])
The GUI components that have callbacks are the list box, toggle button, and plot push button. In addition, the figure's three uipanels define resize functions that MATLAB executes whenever users resize the figure.
See Programming the Resize Functions for information on writing callback functions for the figure and uipanel ResizeFcn properties.
List Box Callback. The list box callback generates a list of the current variables in the base workspace using the evalin and who functions. It then assigns this list to the list box String property so that it displays these variable names.
The function takes advantage of the fact that the first argument passed to the callback is the handle of the callback object (i.e., the source of the callback event, which is the list box). Therefore, whenever you click in the list box, MATLAB updates the list to display the current workspace variables.
%% Callback for list box function listBoxCallback(src,evt) % Load workspace vars into list box vars = evalin('base','who'); set(src,'String',vars) end % listBoxCallback
Plot Button Callback. The plot button callback performs three tasks:
Gets the names of the variables selected by the user in the list box.
Gets the type of plot selected by the user in the pop-up menu.
Constructs and evaluates the plotting command in the base workspace:
%% Callback for plot button function plotButtonCallback(src,evt) % Get workspace variables vars = get(listBox,'String'); var_index = get(listBox,'Value'); if length(var_index) ~= 2 errordlg('You must select two variables',... 'Incorrect Selection','modal') return end % Get data from base workspace x = evalin('base',vars{var_index(1)}); y = evalin('base',vars{var_index(2)}); % Get plotting command selected_cmd = get(popUp,'Value'); % Make the GUI axes current and create plot axes(a) switch selected_cmd case 1 % user selected plot plot(x,y) case 2 % user selected bar bar(x,y) case 3 % user selected stem stem(x,y) end end % plotButtonCallback
Hold State Toggle Button Callback. The toggle button callback requires the handles of the GUI figure and axes. Because these callbacks are written as nested functions, the figure handle (f) and the axes handle (a) are in scope within the callback.
You want the GUI to toggle the hold state, but the GUI figure handle is hidden. It is necessary, therefore, to use the axes handle as the first argument to the hold function.
%% Callback for hold state toggle button function holdToggleCallback(src,evt) button_state = get(src,'Value'); if button_state == get(src,'Max') % toggle button is depressed hold(a,'on') set(src,'String','Hold On') elseif button_state == get(src,'Min') % toggle button is not depressed hold(a,'off') set(src,'String','Hold Off') end end % holdToggleCallback
![]() | Callback Properties for Graphics Objects | Optimizing Graphics Performance | ![]() |

Includes the most popular MATLAB recorded presentations with Q&A sessions led by MATLAB experts.
| © 1984-2009- The MathWorks, Inc. - Site Help - Patents - Trademarks - Privacy Policy - Preventing Piracy - RSS |