| MATLAB® | ![]() |
| On this page… |
|---|
This example contains only a push button. Clicking the button, closes the GUI.

This is the push button's Callback callback. It displays the string Goodbye at the command line and then closes the GUI.
function pushbutton1_Callback(hObject, eventdata, handles) display Goodbye close(handles.figure1);
To add an image to a push button or toggle button, assign the button's CData property an m-by-n-by-3 array of RGB values that defines RGB (Truecolor) Images. For example, the array a defines 16-by-64 truecolor image using random values between 0 and 1 (generated by rand).
a(:,:,1) = rand(16,64); a(:,:,2) = rand(16,64); a(:,:,3) = rand(16,64); set(hObject,'CData',a)

To add the image when the button is created, add the code to the button's CreateFcn callback. You may want to delete the value of the button's String property, which would usually be used as a label.
See ind2rgb for information on converting a matrix X and corresponding colormap, i.e., an (X, MAP) image, to RGB (truecolor) format.
The callback for a toggle button needs to query the toggle button to determine what state it is in. The Value property is equal to the Max property when the toggle button is pressed and equal to the Min property when the toggle button is not pressed.
The following code illustrates how to program the callback in the GUI M-file.
function togglebutton1_Callback(hObject, eventdata, handles)
button_state = get(hObject,'Value');
if button_state == get(hObject,'Max')
% Toggle button is pressed, take approperiate action
...
elseif button_state == get(hObject,'Min')
% Toggle button is not pressed, take appropriate action
...
endYou can also change the state of a toggle button programmatically by setting the toggle button Value property to the value of its Max or Min property. This example illustrates a possible syntax for such an assignment.
set(handles.togglebutton1,'Value','Max')
puts the toggle button with Tag property togglebutton1 in the pressed state.
Note You can use a button group to manage exclusive selection behavior for toggle buttons. See Button Group for more information. |
You can determine the current state of a radio button from within its Callback callback by querying the state of its Value property. If the radio button is selected, its Value property is equal to its Max property. If the radio button is not selected, it is equal to its Min property. This example illustrates such a test.
function radiobutton1_Callback(hObject, eventdata, handles) if (get(hObject,'Value') == get(hObject,'Max')) % Radio button is selected, take appropriate action else % Radio button is not selected, take appropriate action end
You can also change the state of a radio button programmatically by setting the radio button Value property to the value of the Max or Min property. This example illustrates a possible syntax for such an assignment.
set(handles.radiobutton1,'Value','Max')
selects the radio button with Tag property radiobutton1 and deselects the previously selected radio button.
Note You can use a button group to manage exclusive selection behavior for radio buttons. See Button Group for more information. |
You can determine the current state of a check box from within its callback by querying the state of its Value property. The Value property is equal to the Max property when the check box is checked and equal to the Min property when the check box is not checked. This example illustrates such a test.
function checkbox1_Callback(hObject, eventdata, handles) if (get(hObject,'Value') == get(hObject,'Max')) % Checkbox is checked-take approriate action else % Checkbox is not checked-take approriate action end
You can also change the state of a check box programmatically by setting the check box Value property to the value of the Max or Min property. This example illustrates a possible syntax for such an assignment.
set(handles.checkbox1,'Value','Max')
puts the check box with Tag property checkbox1 in the checked state.
To obtain the string a user types in an edit box, get the String property in the Callback callback.
function edittext1_Callback(hObject, eventdata, handles) user_string = get(hObject,'String'); % Proceed with callback
If the edit text Max and Min properties are set such that Max - Min > 1, the user can enter multiple lines. For example, setting Max to 2, with the default value of 0 for Min, enables users to enter multiple lines.
MATLAB® software returns the value of the edit text String property as a character string. If you want users to enter numeric values, you must convert the characters to numbers. You can do this using the str2double command, which converts strings to doubles. If the user enters nonnumeric characters, str2double returns NaN.
You can use the following code in the edit text callback. It gets the value of the String property and converts it to a double. It then checks whether the converted value is NaN (isnan), indicating the user entered a nonnumeric character and displays an error dialog (errordlg).
function edittext1_Callback(hObject, eventdata, handles)
user_entry = str2double(get(hObject,'string'));
if isnan(user_entry)
errordlg('You must enter a numeric value','Bad Input','modal')
return
end
% Proceed with callback...If the contents of the edit text component have been changed, clicking inside the GUI but outside the edit text causes the edit text callback to execute. The user can also press Enter for an edit text that allows only a single line of text, or Ctrl+Enter for an edit text that allows multiple lines.
GUI users can use the following keyboard accelerators to modify the content of an edit text. These accelerators are not modifiable.
Ctrl+X — Cut
Ctrl+C — Copy
Ctrl+V — Paste
Ctrl+H — Delete last character
Ctrl+A — Select all
You can determine the current value of a slider from within its callback by querying its Value property, as illustrated in the following example:
function slider1_Callback(hObject, eventdata, handles) slider_value = get(hObject,'Value'); % Proceed with callback...
The Max and Min properties specify the slider's maximum and minimum values. The slider's range is Max - Min.
When the list box Callback callback is triggered, the list box Value property contains the index of the selected item, where 1 corresponds to the first item in the list. The String property contains the list as a cell array of strings.
This example retrieves the selected string. It assumes listbox1 is the value of the Tag property. Note that it is necessary to convert the value returned from the String property from a cell array to a string.
function listbox1_Callback(hObject, eventdata, handles)
index_selected = get(hObject,'Value');
list = get(hObject,'String');
item_selected = list{index_selected}; % Convert from cell array
% to stringYou can also select a list item programmatically by setting the list box Value property to the index of the desired item. For example,
set(handles.listbox1,'Value',2)
selects the second item in the list box with Tag property listbox1.
MATLAB software executes the list box's Callback callback after the mouse button is released or after certain key press events:
The arrow keys change the Value property, trigger callback execution, and set the figure SelectionType property to normal.
The Enter key and space bar do not change the Value property but trigger callback execution and set the figure SelectionType property to open.
If the user double-clicks, the callback executes after each click. The software sets the figure SelectionType property to normal on the first click and to open on the second click. The callback can query the figure SelectionType property to determine if it was a single or double click.
See the following examples for more information on using list boxes:
List Box Directory Reader — Shows how to creates a GUI that displays the contents of directories in a list box and enables users to open a variety of file types by double-clicking the filename.
Accessing Workspace Variables from a List Box — Shows how to access variables in the MATLAB base workspace from a list box GUI.
When the pop-up menu Callback callback is triggered, the pop-up menu Value property contains the index of the selected item, where 1 corresponds to the first item on the menu. The String property contains the menu items as a cell array of strings.
Note A pop-up menu is sometimes referred to as a drop-down menu or combo box. |
This example retrieves only the index of the item selected. It uses a switch statement to take action based on the value. If the contents of the pop-up menu are fixed, then you can use this approach. Else, you can use the index to retrieve the actual string for the selected item.
function popupmenu1_Callback(hObject, eventdata, handles) val = get(hObject,'Value'); switch val case 1 % User selected the first item case 2 % User selected the second item % Proceed with callback...
You can also select a menu item programmatically by setting the pop-up menu Value property to the index of the desired item. For example,
set(handles.popupmenu1,'Value',2)
selects the second item in the pop-up menu with Tag property popupmenu1.
This example retrieves the actual string selected in the pop-up menu. It uses the pop-up menu Value property to index into the list of strings. This approach may be useful if your program dynamically loads the contents of the pop-up menu based on user action and you need to obtain the selected string. Note that it is necessary to convert the value returned by the String property from a cell array to a string.
function popupmenu1_Callback(hObject, eventdata, handles)
val = get(hObject,'Value');
string_list = get(hObject,'String');
selected_string = string_list{val}; % Convert from cell array
% to string
% Proceed with callback...Panels group GUI components and can make a GUI easier to understand by visually grouping related controls. A panel can contain panels and button groups as well as axes and user interface controls such as push buttons, sliders, pop-up menus, etc. The position of each component within a panel is interpreted relative to the lower-left corner of the panel.
Generally, if the GUI is resized, the panel and its components are also resized. However, you can control the size and position of the panel and its components. You can do this by setting the GUI Resize behavior to Other (Use ResizeFcn) and providing a ResizeFcn callback for the panel.
Note To set Resize behavior for the figure to Other (Use ResizeFcn), select GUI Options from the Layout Editor Tools menu. See Cross-Platform Compatible Units for information about the effect of units on resize behavior. |
Button groups are like panels except that they manage exclusive selection behavior for radio buttons and toggle buttons. If a button group contains a set of radio buttons, toggle buttons, or both, the button group allows only one of them to be selected. When a user clicks a button, that button is selected and all others are deselected.
The following figure shows a button group with two radio buttons and two toggle buttons. Radio Button 1 is selected.

If a user clicks the other radio button or one of the toggle buttons, it becomes selected and Radio Button 1 is deselected. The following figure shows the result of clicking Toggle Button 2.

The button group's SelectionChangeFcn callback is called whenever a selection is made. Its hObject input argument contains the handle of the selected radio button or toggle button.
If you have a button group that contains a set of radio buttons and toggle buttons and you want:
An immediate action to occur when a radio button or toggle button is selected, you must include the code to control the radio and toggle buttons in the button group's SelectionChangeFcn callback function, not in the individual toggle button Callback functions. Color Palette provides a practical example of a SelectionChangeFcn callback.
Another component such as a push button to base its action on the selection, then that component's Callback callback can get the handle of the selected radio button or toggle button from the button group's SelectedObject property.
This example of a SelectionChangeFcn callback uses the Tag property of the selected object to choose the appropriate code to execute. For GUIDE GUIs, unlike other callbacks, the hObject argument of the SelectionChangeFcn callback contains the handle of the selected radio button or toggle button.
function uibuttongroup1_SelectionChangeFcn(hObject,...
eventdata,handles)
switch get(hObject,'Tag') % Get Tag of selected object
case 'radiobutton1'
% Code for when radiobutton1 is selected.
case 'radiobutton2'
% Code for when radiobutton2 is selected.
case 'togglebutton1'
% Code for when togglebutton1 is selected.
case 'togglebutton2'
% Code for when togglebutton2 is selected.
% Continue with more cases as necessary.
otherwise
% Code for when there is no match.
endSee the uibuttongroup reference page for another example.
Axes components enable your GUI to display graphics, such as graphs and images. This topic briefly tells you how to plot to axes components in your GUI.
In most cases, you create a plot in an axes from a callback that belongs to some other component in the GUI. For example, pressing a button might trigger the plotting of a graph to an axes. In this case, the button's Callback callback contains the code that generates the plot.
The following example contains two axes and two buttons. Clicking one button generates a plot in one axes and clicking the other button generates a plot in the other axes. The following figure shows these components as they might appear in the Layout Editor.

Add this code to the Plot 1 push button's Callback callback. The surf function produces a 3-D shaded surface plot. The peaks function returns a square matrix obtained by translating and scaling Gaussian distributions.
surf(handles.axes1,peaks(35));
Add this code to the Plot 2 push button's Callback callback. The contour function displays the contour plot of a matrix, in this case the output of peaks.
contour(handles.axes2,peaks(35));
Click the Plot 1 button to display the surf plot in the first axes. Click the Plot 2 button to display the contour plot in the second axes.

See GUI with Multiple Axes for a more complex example that uses two axes.
Note For information about properties that you can set to control many aspects of axes behavior and appearance, see Axes Properties in the MATLAB Graphics documentation. For information about plotting in general, see Plots and Plotting Tools in the MATLAB Graphics documentation. |
If your GUI contains axes, you should make sure that the Command-line accessibility option in the GUI Options dialog box is set to Callback (the default). From the Layout Editor select Tools > GUI Options > Command Line Accessibility: Callback. See Command-Line Accessibility for more information about how this option works.
Use the subplot function to create axes in a tiled pattern. If your GUIDE-generated GUI contains components other than the subplots, the subplots must be contained in a panel.
As an example, the following code uses the subplot function to create an axes with two subplots in the panel with Tag property uipanel1. This code is part of the Plot push button Callback callback. Each time you press the Plot button, the code draws a line in each subplot. a1 and a2 are the handles of the subplots.
a1=subplot(2,1,1,'Parent',handles.uipanel1); plot(a1,rand(1,10),'r'); a2=subplot(2,1,2,'Parent',handles.uipanel1); plot(a2,rand(1,10),'b');

For more information about subplots, see the subplot reference page. For information about adding panels to your GUI, see Adding Components to the GUIDE Layout Area.
This example programs a sample ActiveX® control Mwsamp Control. It first enables a user to change the radius of a circle by clicking on the circle. It then programs a slider on the GUI to do the same thing.
This topic also discusses:
Note See Creating COM Objects in the MATLAB External Interfaces documentation to learn more about ActiveX controls. |
The sample ActiveX control Mwsamp Control contains a circle in the middle of a square. This example programs the control to change the circle radius when the user clicks the circle, and to update the label to display the new radius.
Add the sample ActiveX control Mwsamp to your GUI and resize it to approximately the size of the square shown in the preview pane. The following figure shows the ActiveX control as it appears in the Layout Editor.
If you need help adding the component, see Adding Components to the GUIDE Layout Area.

Activate the GUI by clicking the
button on the toolbar and save the
GUI when prompted. GUIDE displays the GUI shown in the following figure
and opens the GUI M-file.

View the ActiveX Properties
with the Property Inspector. Select the control in the Layout Editor,
and then select Property Inspector from
the View menu or by clicking the Property Inspector button
on the toolbar.
The following figure shows properties of the mwsamp ActiveX control as they appear in the Property Inspector. The properties on your system may differ.

This ActiveX control mwsamp has two properties:
Label, which contains the text that appears at the top of the control
Radius, the default radius of the circle, which is 20
Add the following code to the mswamp control's Click callback. This code programs the ActiveX control to change the circle radius when the user clicks the circle, and updates the label to display the new radius.
hObject.radius = .9*hObject.radius; hObject.label = ['Radius = ' num2str(hObject.radius)]; refresh(handles.figure1);
To locate the Click callback in the GUI M-file, select View Callbacks from the View menu and then select Click.
Add the following commands to the opening function. This code initializes the label when you first open the GUI.
handles.activex1.label = ... ['Radius = ' num2str(handles.activex1.radius)];
Save the M-file. Now, when you open the GUI and click the ActiveX control, the radius of the circle is reduced by 10 percent and the new value of the radius is displayed. The following figure shows the GUI after clicking the circle six times.

If you click the GUI enough times, the circle disappears.
This topic continues the previous example by adding a slider to the GUI and programming the slider to change the circle radius. This example must also update the slider if the user clicks the circle.
Add a slider to your layout and then add the following code to the slider1 Callback callback:
handles.activex1.radius = ...
get(hObject,'Value')*handles.default_radius;
handles.activex1.label = ...
['Radius = ' num2str(handles.activex1.radius)];
refresh(handles.figure1);The first command
Gets the Value of the slider, which in this example is a number between 0 and 1, the default values of the slider's Min and Max properties.
Sets handles.activex1.radius equal to the Value times the default radius.
In the opening function, add the default radius to the handles structure. The activex1_Click callback uses the default radius to update the slider value if the user clicks the circle.
handles.default_radius = handles.activex1.radius;
In the activex1_Click callback, reset the slider's Value each time the user clicks the circle in the ActiveX control. The following command causes the slider to change position corresponding to the new value of the radius.
set(handles.slider1,'Value',...
hObject.radius/handles.default_radius);When you open the GUI and move the slider by clicking and dragging, the radius changes to a new value between 0 and the default radius of 20, as shown in the following figure.

To view the available methods for an ActiveX control, you first need to obtain the handle to the control. One way to do this is the following:
In the GUI M-file, add the command keyboard on a separate line of the activex1_Click callback. The command keyboard puts MATLAB software in debug mode and pauses at the activex1_Click callback when you click the ActiveX control.
Run the GUI and click the ActiveX control. The handle to the control is now set to hObject.
To view the methods for the control, enter
methodsview(hObject)
This displays the available methods in a new window, as shown in the following figure.

Alternatively, you can enter
methods(hObject)
which displays the available methods in the MATLAB Command Window.
For more information about methods for ActiveX controls, see Using Methods in the External Interfaces documentation. See the reference pages for methodsview and methods for more information about these functions.
When you save a GUI that contains ActiveX controls, GUIDE creates a file in the current directory for each such control. The filename consists of the name of the GUI followed by an underscore (_) and activexn, where n is a sequence number. For example, if the GUI is named mygui, then the filename would be mygui_activex1. The filename does not have an extension.
If you use the MATLAB Compiler mcc command to compile a GUI that contains an ActiveX control, you must use the -a flag to add the ActiveX file, which GUIDE saves in the current directory, to the CTF archive. Your command should be similar to
mcc -m mygui -a mygui_activex1
where mygui_activex1 is the name of the ActiveX file. See the MATLAB Compiler™ documentation for more information. If you have more than one such file, use a separate -a flag for each file. You must have installed the MATLAB Compiler to compile a GUI.
The Menu Editor generates an empty callback subfunction for every menu item, including menu titles.
Because clicking a menu title automatically displays the menu below it, you may not need to program callbacks at the title level. However, the callback associated with a menu title can be a good place to enable or disable menu items below it.
Consider the example illustrated in the following picture.

When a user selects the to file option under the Edit menu's Copy option, only the to file callback is required to perform the action.
Suppose, however, that only certain objects can be copied to a file. You can use the Copy item Callback callback to enable or disable the to file item, depending on the type of object selected.
The Callback callback for the to file menu item could contain code such as the following to display the standard dialog box for saving files.
[file,path] = uiputfile('animinit.m','Save file name');'Save file name' is the dialog box title. In the dialog box, the filename field is set to animinit.m, and the filter set to M-files (*.m). For more information, see the uiputfile reference page.

A check is useful to indicate the current state of some menu items. If you selected Check mark this item in the Menu Editor, the item initially appears checked. Each time the user selects the menu item, the callback for that item must turn the check on or off. The following example shows you how to do this by changing the value of the menu item's Checked property.
if strcmp(get(hObject, 'Checked'),'on')
set(hbject,'Checked','off');
else
set(hObject,'Checked','on');
endhObject is the handle of the component, for which the callback was triggered. The strcmp function compares two strings and returns logical 1 (true) if the two are identical and logical 0 (false) otherwise.
Use of checks when the GUI is first displayed should be consistent with the display. For example, if your GUI has an axes that is visible when a user first opens it and the GUI has a Show axes menu item, be sure to set the menu item's Checked property on when you create it so that a check appears next to the Show axes menu item initially.
Note From the Menu Editor, you can view a menu item's Callback callback in your editor by selecting the menu item and clicking the View button. |
![]() | Initialization Callbacks | Managing and Sharing Application Data in GUIDE | ![]() |
| © 1984-2008- The MathWorks, Inc. - Site Help - Patents - Trademarks - Privacy Policy - Preventing Piracy - RSS |