Graphics Previous page   Next Page

Why Use Function Handle Callbacks

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.

Single File for All Code

Function handles enable you to use a single M-file for all callbacks. This is particularly 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 the Calling a Function Through Its Handle section of "Programming and Data Types" in the Using MATLAB documentation.

Keeping Variables in Scope

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.

  1. Create the list box and save the handle:
  2. Pass the list box handle to the push button's callback, which is defined in the same M-file:

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.

Callback Object Handle and Event Data

MATLAB passes additional information to the callback when it is executed. 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.

Function Handles Stay in Scope

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.

Previous page  Function Handle Syntax Example -- Using Function Handles in GUIs Next page

© 1994-2005 The MathWorks, Inc.