Write Callbacks Using the Programmatic Workflow
Like callbacks specified as function handles, MATLAB checks callbacks specified as cell
arrays for syntax errors and missing dependencies when you assign the callback to the
component. If there is a problem in the callback function, then MATLAB returns an error
immediately instead of waiting for the end user to trigger the callback. This behavior
helps you to find problems in your code before the end user encounters them.
Specify a String of MATLAB Commands (Not Recommended)
You can use string callbacks for a few simple commands, but the callback can become
difficult to manage if it contains more than a few commands. The string you specify must
consist of valid MATLAB expressions, which can include arguments to functions. For
example:
hb = uicontrol('Style','pushbutton',...
'String','Plot line',...
'Callback','plot(rand(20,3))');
The callback string, 'plot(rand(20,3))', is a valid command, and MATLAB
evaluates it when the end user clicks the button. If the callback string includes a
variable, for example,
'plot(myvar)'
The variable, myvar, must exist in the base workspace when the end user triggers the
callback, or it returns an error. The variable does not need to exist at the time you assign
callback property value, but it must exist when the end user triggers the callback.
Unlike callbacks that are specified as function handles or cell arrays, MATLAB does not
check string callbacks for syntax errors or missing dependencies. If there is a problem
with the code in your string, it remains undetected until the end user triggers the
callback.
Callback Syntax
All callback functions that you reference as function handles or cell arrays must
accept the at least two input arguments, hObject and callbackdata. All other input
arguments must appear after hObject and callbackdata in the function definition.
The hObject argument is a handle to the UI component that triggered the callback.
The callbackdata argument provides additional information to certain callback
functions. For example, if the end user triggers the KeyPressFcn, then MATLAB
provides information regarding the specific key (or combination of keys) that the end user
pressed. If callbackdata is not available to the callback function, then MATLAB passes