11 Code a Programmatic UI
disp(['Slider moved to ' newval]);
end
This callback function displays the value of the slider when the end user adjusts it.
A benefit of specifying callbacks as function handles is that MATLAB checks the
function 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.
Note:If you want to use an existing function that does not support the hObject and
callbackdata arguments, then you can specify it as an anonymous function. For
example,
uicontrol('Style','slider','Callback',@(hObject,callbackdata)myfunction(x));
In this case, x is an input argument to the function, myfunction. See “Anonymous
Functions” for more information.
Specify a Cell Array
Use a cell array to specify a callback function that accepts input arguments that you
want to use in the function. The first element in the cell array is a function handle.
The other elements in the cell array are the input arguments to the function, separated
by commas. For example, this code creates a push button component and specifies its
callback to be a cell array containing the function handle, @pushbutton_callback, and
one input argument, myvar. To see how it works, copy and paste this code into an editor
and run it.
function myui()
myvar = 5;
figure
uicontrol('Style','pushbutton',...
'Callback',{@pushbutton_callback,myvar});
end
function pushbutton_callback(hObject,callbackdata,x)
display(x);
end
The function definition must define two input arguments, hObject and callbackdata,
followed by any additional arguments the function uses. Handle Graphics automatically
passes the hObject and callbackdata arguments when it calls the function. If you
define additional input arguments, then the values you pass to the callback must exist in
the workspace when the end user triggers the callback.