Graphics    

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 creating graphical user interfaces since you can include both the layout commands and callbacks in one file.

For information on how to access subfunctions, see the Evaluating a Function Through Its Handle section of Programming and Data Types in the 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.

Create the list box and save the handle:

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 a GUI for an example that uses this technique.

Callback Object Handle and Event Data

MATLAB passes additional information to the callback when executed. Currently this information includes the handle of the callback object, however, later MATLAB releases will include additional event data.

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 may be a subfunction in another M-file.

For a general discussion of the advantages function handles provide, see the Benefits of Function Handles section of Programming and Data Types in the MATLAB documentation.


  Function Handle Callbacks Example -- Using Function Handles in a GUI