MATLAB Creating Graphical User Interfaces

(ff) #1

arguments as described in “Specify a Function Handle” on page 10-7. However, you can
define additional inputs in your function declaration after the first two arguments.


This uicontrol command creates a push button and specifies the Callback property to
be a cell array. In this case, the name of the function is pushbutton_callback, and the
value of the additional input argument is 5.


b = uicontrol('Style','pushbutton','Callback',{@pushbutton_callback,5});


Here is the function definition for pushbutton_callback:


function pushbutton_callback(src,event,x)
display(x);
end


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 user to trigger the callback. This behavior helps
you to find problems in your code before the user encounters them.


Specify an Anonymous Function


Specify an anonymous function when you want a UI component to execute a function that
does not support the two arguments that are required for function handles and cell
arrays. For example, this uicontrol command creates a push button and specifies the
Callback property to be an anonymous function. In this case, the name of function is
myfun, and its function declaration defines only one input argument, x.


b = uicontrol('Style','pushbutton','Callback',@(src,event)myfun(x));


Specify a Character Vector Containing MATLAB Commands (Not Recommended)


You can specify a character vector when you want to execute a few simple commands, but
the callback can become difficult to manage if it contains more than a few commands. The
character vector 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))');


Write Callbacks for Apps Created Programmatically
Free download pdf