Build Gui
Build Gui
Build Gui
App Building
R2016a
www.mathworks.com
www.mathworks.com/sales_and_services
User community:
www.mathworks.com/matlabcentral
Technical support:
www.mathworks.com/support/contact_us
Phone:
508-647-7000
Trademarks
MATLAB and Simulink are registered trademarks of The MathWorks, Inc. See
www.mathworks.com/trademarks for a list of additional trademarks. Other product or brand
names may be trademarks or registered trademarks of their respective holders.
Patents
MathWorks products are protected by one or more U.S. patents. Please see
www.mathworks.com/patents for more information.
Revision History
November 2000
June 2001
July 2002
June 2004
October 2004
March 2005
September 2005
March 2006
May 2006
September 2006
March 2007
September 2007
March 2008
October 2008
March 2009
September 2009
March 2010
September 2010
April 2011
September 2011
March 2012
September 2012
March 2013
September 2013
March 2014
October 2014
March 2015
September 2015
March 2016
Online Only
Online Only
Online Only
Online Only
Online Only
Online Only
Online Only
Online Only
Online Only
Online Only
Online Only
Online Only
Online Only
Online Only
Online Only
Online Only
Online Only
Online Only
Online Only
Online Only
Online Only
Online Only
Online Only
Online Only
Online Only
Online Only
Online Only
Online Only
Online Only
Contents
1-2
1-2
1-3
1-6
2-2
2-3
2-5
2-6
2-16
2-22
2-24
2-24
2-24
2-25
2-26
3-2
3-3
3-3
3-4
3-7
3-11
vi
Contents
What Is GUIDE?
GUIDE: Getting Started . . . . . . . . . . . . . . . . . . . . . . . . . .
UI Layout . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
UI Programming . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
4-2
4-2
4-2
4-3
5-2
5-2
5-2
5-4
5-4
GUIDE Options . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
The GUI Options Dialog Box . . . . . . . . . . . . . . . . . . . . .
Resize Behavior . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
Command-Line Accessibility . . . . . . . . . . . . . . . . . . . . .
5-8
5-8
5-9
5-9
5-10
5-12
6-2
6-2
6-3
6-11
6-11
6-12
6-12
6-13
6-13
6-19
6-40
6-45
6-49
6-60
6-62
6-65
6-65
6-68
6-71
6-72
6-74
6-77
6-77
6-87
6-94
6-94
6-102
vii
viii
Contents
6-106
6-106
6-107
6-107
Programming a GUIDE UI
Write Callbacks in GUIDE . . . . . . . . . . . . . . . . . . . . . . . .
Callbacks for Different User Actions . . . . . . . . . . . . . . .
GUIDE-Generated Callback Functions and Property
Values . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
GUIDE Callback Syntax . . . . . . . . . . . . . . . . . . . . . . . .
Renaming and Removing GUIDE-Generated Callbacks .
7-2
7-2
7-8
7-8
7-10
7-12
7-12
7-13
7-13
7-14
7-15
7-15
7-16
7-17
7-19
7-21
7-22
7-23
7-26
7-27
7-30
7-4
7-5
7-6
8-2
8-2
8-3
8-5
8-7
8-7
8-9
8-11
8-14
8-17
8-17
8-19
8-33
8-33
8-34
8-39
8-39
8-40
8-41
8-44
8-44
8-46
ix
Contents
9-2
9-2
9-2
9-3
9-4
9-6
9-6
9-18
9-19
9-21
9-23
9-25
9-25
9-28
9-28
9-33
9-36
9-37
9-37
9-37
9-39
9-41
9-41
9-48
9-54
9-54
9-54
9-55
9-58
10
11
9-61
9-61
9-62
9-63
9-63
9-65
9-66
Code a Programmatic UI
Initialize a Programmatic UI . . . . . . . . . . . . . . . . . . . . .
Examples . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
10-2
10-2
10-5
10-5
10-7
10-9
11-2
11-2
11-3
11-7
11-12
11-13
11-16
xi
12
12-2
12-2
12-2
12-3
App Designer
13
xii
Contents
13-2
13-5
13-5
13-5
13-5
13-6
13-7
13-7
13-7
13-8
13-8
13-9
13-9
13-10
13-11
13-11
13-12
14
15
14-2
14-2
14-3
14-5
14-5
14-6
14-6
14-8
14-8
14-9
14-9
14-11
14-11
14-15
14-17
14-20
14-22
App Layout
Add and Delete Components Using App Designer . . . .
Add Components . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
Delete Components . . . . . . . . . . . . . . . . . . . . . . . . . . .
Multiselect Components . . . . . . . . . . . . . . . . . . . . . . .
Component Copies and Property Values . . . . . . . . . . .
Effect of Component Deletion on Callback Function
Code . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
15-2
15-2
15-3
15-3
15-4
15-5
15-6
15-6
15-4
xiii
16
xiv
Contents
Space Components . . . . . . . . . . . . . . . . . . . . . . . . . . .
Resize Design Area or Components . . . . . . . . . . . . . .
15-10
15-11
15-13
15-14
15-15
15-16
App Programming
App Designer Code Generation . . . . . . . . . . . . . . . . . . .
16-2
16-5
16-5
16-6
16-8
16-10
16-13
16-14
16-15
16-16
16-19
16-19
16-24
16-24
16-28
16-29
16-13
16-31
16-31
16-34
16-39
16-42
16-45
16-48
Keyboard Shortcuts
17
17-2
17-2
17-2
17-3
17-7
App Packaging
18
18-2
18-2
18-2
18-3
18-4
Package Apps . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
18-5
Modify Apps . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
18-8
Share Apps . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
18-9
xv
xvi
Contents
18-10
Dependency Analysis . . . . . . . . . . . . . . . . . . . . . . . . . . .
18-11
1
About Apps in MATLAB Software
Use GUIDE
GUIDE is a drag-and-drop environment for laying out user interfaces (UIs). You code
the interactive behavior of your app separately, in the MATLAB editor. Apps you create
using GUIDE can display any type of MATLAB plot. GUIDE also provides various
interactive components, including menus, tool bars, and tables. Use this approach to
create simple apps that can display any type of plot.
1-2
panels. Use this approach to build complex apps with many interdependent components
that can display any type of plot.
1-4
1-5
1-6
Related Examples
More About
1-7
2
How to Create a App with GUIDE
Subsequent sections guide you through the process of creating this app.
If you only want to view and run the code that created this app, set your current folder to
one to which you have write access. Copy the example code and open it in the Editor by
issuing the following MATLAB commands:
copyfile(fullfile(docroot, 'techdoc','creating_guis',...
'examples','simple_gui*.*')),fileattrib('simple_gui*.*', '+w');
guide simple_gui.fig;
edit simple_gui.m
In the GUIDE Quick Start dialog box, select the Blank (Default) template, and
then click OK.
2-3
2-4
Click OK.
2-5
Layout the UI
Add, align, and label the components in the UI.
1
2-6
Add the three push buttons to the UI. Select the push button tool from the
component palette at the left side of the Layout Editor and drag it into the layout
area. Create three buttons, positioning them approximately as shown in the
following figure.
2-7
Select all three push buttons by pressing Ctrl and clicking them.
2-8
Click OK.
2-9
2-10
In the Property Inspector, select the String property, and then replace the existing
value with the word Surf.
Click outside the String field. The push button label changes to Surf.
2-11
Click each of the remaining push buttons in turn and repeat steps 3 and 4. Label the
middle push button Mesh, and the bottom button Contour.
2-12
In the Property Inspector, click the button next to String. The String dialog box
displays.
Replace the existing text with the names of the three data sets: peaks, membrane,
and sinc. Press Enter to move to the next line.
In the Property Inspector, click the button next to String. In the String dialog box
that displays, replace the existing text with the phrase Select Data.
2-13
Click OK.
The phrase Select Data appears in the static text component above the pop-up
menu.
2-14
GUIDE displays a dialog box displaying: Activating will save changes to your figure
file and MATLAB code. Do you wish to continue?
Click Yes.
3
GUIDE opens a Save As dialog box in your current folder and prompts you for a
FIG-file name.
Browse to any folder for which you have write privileges, and then enter the file
name simple_gui for the FIG-file. GUIDE saves both the FIG-file and the code file
using this name.
If the folder in which you save the files is not on the MATLAB path, GUIDE opens a
dialog box that allows you to change the current folder.
GUIDE saves the files simple_gui.fig and simple_gui.m, and then runs the
program. It also opens the code file in your default editor.
The app opens in a new window. Notice that the window lacks the standard menu
bar and toolbar that MATLAB figure windows display. You can add your own menus
and toolbar buttons with GUIDE, but by default a GUIDE app includes none of these
components.
When you run simple_gui, you can select a data set in the pop-up menu and click
the push buttons, but nothing happens. This is because the code file contains no
statements to service the pop-up menu and the buttons.
2-15
To run an app created with GUIDE without opening GUIDE, execute its code file by
typing its name.
simple_gui
You can also use the run command with the code file, for example,
run simple_gui
Note: Do not attempt to run your app by opening its FIG-file outside of GUIDE. If you
do so, the figure opens and appears ready to use, but the UI does not initialize and the
callbacks do not function.
2-16
On the EDITOR tab, in the NAVIGATE section, click Go To, and then select
simple_gui_OpeningFcn.
The cursor moves to the opening function, which contains this code:
% --- Executes just before simple_gis made visible.
function simple_gui_OpeningFcn(hObject, eventdata, handles, varargin)
% This function has no output args, see OutputFcn.
% hObject
handle to figure
% eventdata reserved - to be defined in a future version of MATLAB
% handles
structure with handles and user data (see GUIDATA)
% varargin
command line arguments to simple_g(see VARARGIN)
% Choose default command line output for simple_gui
handles.output = hObject;
% Update handles structure
guidata(hObject, handles);
% UIWAIT makes simple_gwait for user response (see UIRESUME)
% uiwait(handles.figure1);
Create data to plot by adding the following code to the opening function immediately
after the comment that begins % varargin...
% Create the data to plot.
handles.peaks=peaks(35);
handles.membrane=membrane;
[x,y] = meshgrid(-8:.5:8);
r = sqrt(x.^2+y.^2) + eps;
sinc = sin(r)./r;
handles.sinc = sinc;
% Set the current data value.
2-17
handles.current_data = handles.peaks;
surf(handles.current_data)
The first six executable lines create the data using the MATLAB functions peaks,
membrane, and sinc. They store the data in the handles structure, an argument
provided to all callbacks. Callbacks for the push buttons can retrieve the data from
the handles structure.
The last two lines create a current data value and set it to peaks, and then display
the surf plot for peaks. The following figure shows how the looks when it first
displays.
2-18
Display the pop-up menu callback in the MATLAB Editor. In the GUIDE Layout
Editor, right-click the pop-up menu component, and then select View Callbacks >
Callback.
GUIDE displays the code file in the Editor, and moves the cursor to the pop-menu
callback, which contains this code:
% --- Executes on selection change in popupmenu1.
function popupmenu1_Callback(hObject, eventdata, handles)
% hObject
handle to popupmenu1 (see GCBO)
% eventdata reserved - to be defined in a future version of MATLAB
% handles
structure with handles and user data (see GUIDATA)
Add the following code to the popupmenu1_Callback after the comment that begins
% handles...
2-19
2-20
Display the Surf push button callback in the MATLAB Editor. In the Layout Editor,
right-click the Surf push button, and then select View Callbacks > Callback.
In the Editor, the cursor moves to the Surf push button callback in the code file,
which contains this code:
% --- Executes on button press in pushbutton1.
function pushbutton1_Callback(hObject, eventdata, handles)
% hObject
handle to pushbutton1 (see GCBO)
% eventdata reserved - to be defined in a future version of MATLAB
% handles
structure with handles and user data (see GUIDATA)
Add the following code to the callback immediately after the comment that begins %
handles...
% Display surf plot of the currently selected data.
surf(handles.current_data);
Repeat steps 1 and 2 to add similar code to the Mesh and Contour push button
callbacks.
2-21
2-22
Run your program from the Layout Editor by selecting Tools > Run.
In the pop-up menu, select Membrane, and then click the Mesh button. The
displays a mesh plot of the MathWorks L-shaped Membrane logo.
Related Examples
More About
2-23
mygui.m, then the name of the main function is mygui. Each callback in the file is a local
function of that main function.
When GUIDE generates a code file, it automatically includes templates for the most
commonly used callbacks for each component. The code file also contains initialization
code, as well as an opening function callback and an output function callback. It is your
job to add code to the component callbacks for your program to work as you want. You
can also add code to the opening function callback and the output function callback. The
code file orders functions as shown in the following table.
Section
Description
Comments
Initialization
Opening function
Output function
Component and figure Control the behavior of the window and of individual
callbacks
components. MATLAB software calls a callback in response to a
particular event for a component or for the figure itself.
Utility/helper
functions
For toolbar buttons, in the Toolbar Editor, click the View button next to Clicked
Callback (for Push Tool buttons) or On Callback, or Off Callback (for Toggle
Tools).
When you perform any of these actions, GUIDE adds the callback template to the code
file, saves it, and opens it for editing at the callback you just added. If you select a
callback that currently exists in the code file, GUIDE adds no callback, but saves the file
and opens it for editing at the callback you select.
For more information, see GUIDE-Generated Callback Functions and Property Values
on page 7-4.
callback code manually. For details, see Renaming and Removing GUIDE-Generated
Callbacks on page 7-6.
Related Examples
2-27
3
A Simple Programmatic App
Subsequent sections guide you through the process of creating this app.
If you prefer to view and run the code that created this app without creating it, set your
current folder to one to which you have write access. Copy the example code and open it
in the Editor by issuing the following MATLAB commands:
copyfile(fullfile(docroot, 'techdoc','creating_guis',...
'examples','simple_gui2*.*')), fileattrib('simple_gui2*.*', '+w');
3-2
edit simple_gui2.m
Note: This code uses dot notation to set graphics object properties. Dot notation runs in
R2014b and later. If you are using an earlier release, use the set function instead. For
example, change f.Visible = 'on' to set(f,'Visible','on').
To run the code, go to the Run section in the Editor tab. Then click Run
Following the function statement, type these comments, ending with a blank line.
(The comments display at the command line in response to the help command.)
% SIMPLE_GUI2 Select a data set from the pop-up menu, then
% click one of the plot-type push buttons. Clicking the button
% plots the selected data in the axes.
(Leave a blank line here)
At the end of the file, after the blank line, add an end statement. This end statement
is required because the example uses nested functions. To learn more, see Nested
Functions.
Save the file in your current folder or at a location that is on your MATLAB path.
The call to the figure function creates a traditional figure and sets the following
properties:
3-3
The Visible property makes the window invisible so that the user cannot see the
components being added or initialized.
The window becomes visible when the UI has all its components and is initialized.
The Position property is a four-element vector that specifies the location of the UI
on the screen and its size: [distance from left, distance from bottom, width, height].
Default units are pixels.
Following the call to figure, add these statements to your code file to create three
push button components.
% Construct the components.
hsurf
= uicontrol('Style','pushbutton',...
'String','Surf','Position',[315,220,70,25]);
hmesh
= uicontrol('Style','pushbutton',...
'String','Mesh','Position',[315,180,70,25]);
hcontour = uicontrol('Style','pushbutton',...
'String','Contour','Position',[315,135,70,25]);
Add the pop-up menu and its static text label by adding these statements to the code
file following the push button definitions. The first statement creates a popup menu.
The second statement creates a text component that serves as a label for the popup
menu.
htext
3-4
= uicontrol('Style','text','String','Select Data',...
'Position',[325,90,60,15]);
hpopup = uicontrol('Style','popupmenu',...
'String',{'Peaks','Membrane','Sinc'},...
'Position',[300,50,100,25]);
The pop-up menu component String property uses a cell array to specify the three
items in the pop-up menu: Peaks, Membrane, and Sinc.
The text component, the String property specifies instructions for the user.
For both components, the Position property specifies the size and location of each
component: [distance from left, distance from bottom, width, height]. Default units
for these components are pixels.
3
The Units property specifies pixels so that the axes has the same units as the other
components.
4
Following all the component definitions, add this line to the code file to align all
components, except the axes, along their centers.
align([hsurf,hmesh,hcontour,htext,hpopup],'Center','None');
3-5
3-6
Run your code by typing simple_gui2 at the command line. You can select a data
set in the pop-up menu and click the push buttons, but nothing happens. This
is because there is no callback code in the file to service the pop-up menu or the
buttons.
3-7
%
%
%
3-8
To the uicontrol statement that defines the Surf push button, add the property/
value pair
'Callback',{@surfbutton_Callback}
To the uicontrol statement that defines the Mesh push button, add the property/
value pair
'Callback',@meshbutton_Callback
To the uicontrol statement that defines the Contour push button, add the
property/value pair
'Callback',@contourbutton_Callback
To the uicontrol statement that defines the pop-up menu, add the property/value
pair
'Callback',@popup_menu_Callback
For more information, see Write Callbacks for Apps Created Programmatically on page
10-5.
Initialize the UI
Initialize the UI, so it is ready when the window becomes visible. Make the UI behave
properly when it is resized by changing the component and figure units to normalized.
This causes the components to resize when the UI is resized. Normalized units map the
lower-left corner of the figure window to (0,0) and the upper-right corner to (1.0,
1.0).
3-9
Note: This code uses dot notation to set object properties. Dot notation runs in R2014b
and later. If you are using an earlier release, use the set function instead. For example,
change f.Units = 'normalized' to set(f,'Units','normalized').
Replace this code in editor:
% Make the UI visible.
f.Visible = 'on';
3-10
3-11
ha.Units = 'normalized';
hsurf.Units = 'normalized';
hmesh.Units = 'normalized';
hcontour.Units = 'normalized';
htext.Units = 'normalized';
hpopup.Units = 'normalized';
% Generate the data to plot.
peaks_data = peaks(35);
membrane_data = membrane;
[x,y] = meshgrid(-8:.5:8);
r = sqrt(x.^2+y.^2) + eps;
sinc_data = sin(r)./r;
% Create a plot in the axes.
current_data = peaks_data;
surf(current_data);
% Assign the a name to appear in the window title.
f.Name = 'Simple GUI';
% Move the window to the center of the screen.
movegui(f,'center')
% Make the window visible.
f.Visible = 'on';
%
%
%
%
3-12
end
% Push button callbacks. Each callback plots current_data in the
% specified plot type.
function surfbutton_Callback(source,eventdata)
% Display surf plot of the currently selected data.
surf(current_data);
end
function meshbutton_Callback(source,eventdata)
% Display mesh plot of the currently selected data.
mesh(current_data);
end
function contourbutton_Callback(source,eventdata)
% Display contour plot of the currently selected data.
contour(current_data);
end
end
Run your app by typing simple_gui2 at the command line. The initialization code
causes it to display the default peaks data with the surf function, making the UI
look like this.
3-13
In the pop-up menu, select Membrane, and then click the Mesh button. The UI
displays a mesh plot of the MathWorks L-shaped Membrane logo.
Type help simple_gui2 at the command line. MATLAB software displays the help
text.
help simple_gui2
SIMPLE_GUI2 Select a data set from the pop-up menu, then
click one of the plot-type push buttons. Clicking the button
plots the selected data in the axes.
Related Examples
More About
3-14
4
What Is GUIDE?
GUIDE: Getting Started on page 4-2
GUIDE Tools Summary on page 4-3
What Is GUIDE?
UI Layout
GUIDE is a development environment that provides a set of tools for creating user
interfaces (UIs). These tools simplify the process of laying out and programming UIs.
Using the GUIDE Layout Editor, you can populate a UI by clicking and dragging UI
componentssuch as axes, panels, buttons, text fields, sliders, and so oninto the layout
area. You also can create menus and context menus for the UI. From the Layout Editor,
you can size the UI, modify component look and feel, align components, set tab order,
view a hierarchical list of the component objects, and set UI options.
UI Programming
GUIDE automatically generates a program file containing MATLAB functions that
controls how the UI behaves. This code file provides code to initialize the UI, and it
contains a framework for the UI callbacks. Callbacks are functions that execute when
the user interacts with a UI component. Use the MATLAB Editor to add code to these
callbacks.
Note MATLAB software provides a selection of standard dialog boxes that you can create
with a single function call. For an example, see the documentation for msgbox, which
also provides links to functions that create specialized predefined dialog boxes.
4-2
To...
Layout Editor
What Is GUIDE?
To...
Components to the GUIDE Layout Area on page 6-13 for more
information.
Figure Resize
Tab
Set the size at which the UI is initially displayed when you run it.
See Set the UI Window Size in GUIDE on page 6-11 for more
information.
Menu Editor
Create menus and context, i.e., pop-up, menus. See Create Menus for
GUIDE UIs on page 6-77 for more information.
Align Objects
Tab Order
Editor
Set the tab and stacking order of the components in your layout. See
Customize Tabbing Behavior in a GUIDE UI on page 6-74 for
more information.
Toolbar Editor
Icon Editor
Create and modify icons for tools in a toolbar. See Create Toolbars for
GUIDE UIs on page 6-94 for more information.
Property
Inspector
Editor
Display, in your default editor, the code file associated with the UI. See
Files Generated by GUIDE on page 2-24 for more information.
Position
Readouts
Related Examples
More About
4-4
5
GUIDE Preferences and Options
GUIDE Preferences on page 5-2
GUIDE Options on page 5-8
GUIDE Preferences
In this section...
Set Preferences on page 5-2
Confirmation Preferences on page 5-2
Backward Compatibility Preference on page 5-4
All Other Preferences on page 5-4
Set Preferences
You can set preferences for GUIDE. From the MATLAB Home tab, in the Environment
section, click Preferences. These preferences apply to GUIDE and to all UIs you create.
The preferences are in different locations within the Preferences dialog box:
Confirmation Preferences
GUIDE provides two confirmation preferences. You can choose whether you want to
display a confirmation dialog box when you
Activate a UI from GUIDE.
Export a UI from GUIDE.
Change a callback signature generated by GUIDE.
In the Preferences dialog box, click MATLAB > General > Confirmation Dialogs
to access the GUIDE confirmation preferences. Look for the word GUIDE in the Tool
column.
5-2
GUIDE Preferences
5-3
5-4
GUIDE Preferences
5-5
GUIDE Preferences
Some callbacks are added automatically because their associated components are part
of the original GUIDE template that you chose. Other commonly used callbacks are
added automatically when you add components. You can also add callbacks explicitly by
selecting them from View > View Callbacks menu or on the component's context menu.
If you deselect this preference, GUIDE includes comments only for callbacks that are
automatically included to support the original GUIDE template. GUIDE does not include
comments for callbacks subsequently added to the code.
See Write Callbacks in GUIDE on page 7-2 for more information about callbacks
and about the arguments described in the preceding comments.
More About
5-7
GUIDE Options
In this section...
The GUI Options Dialog Box on page 5-8
Resize Behavior on page 5-9
Command-Line Accessibility on page 5-9
Generate FIG-File and MATLAB File on page 5-10
Generate FIG-File Only on page 5-12
5-8
GUIDE Options
Resize Behavior
You can control whether users can resize the window and how MATLAB handles
resizing. GUIDE provides three options:
Non-resizable Users cannot change the window size (default).
Proportional The software automatically scales the components in the UI in
proportion to the new figure window size.
Other (Use SizeChangedFcn) Program the UI to behave in a certain way when
users resize the figure window.
The first two options set figure and component properties appropriately and require no
other action. Other (Use SizeChangedFcn) requires you to write a callback routine
that recalculates sizes and positions of the components based on the new figure size.
Command-Line Accessibility
You can restrict access to a figure window from the command line or from a code file with
the GUIDE Command-line accessibility options.
Unless you explicitly specify a figure handle, many commands, such as plot, alter the
current figure (the figure specified by the root CurrentFigure property and returned by
the gcf command). The current figure is usually the figure that is most recently created,
drawn into, or mouse-clicked. You can programmatically designate a figure h (where h is
its handle) as the current figure in four ways:
1
figure(h) Makes figure h current, visible, and displayed on top of other figures
axes(h) Makes existing axes h the current axes and displays the figure
containing it on top of other figures
plot(h,...), or any plotting function that takes an axes as its first argument, also
makes existing axes h the current axes and displays the figure containing it on top of
other figures
5-9
Description
GUIDE Options
GUIDE also adds a callback whenever you edit a callback routine from the Layout
Editor's right-click context menu and when you add menus to the UI using the Menu
Editor.
See Write Callbacks in GUIDE on page 7-2 for general information about
callbacks.
Note This option is available only if you first select the Generate FIG-file and
MATLAB file option.
GUI Allows Only One Instance to Run (Singleton)
This option allows you to select between two behaviors for the figure window:
Allow MATLAB software to display only one instance of the UI at a time.
Allow MATLAB software to display multiple instances of the UI.
If you allow only one instance, the software reuses the existing figure whenever the
command to run your program is executed. If a UI window already exists, the software
brings it to the foreground rather than creating a new figure.
If you clear this option, the software creates a new figure whenever you issue the
command to run the program.
Even if you allow only one instance of a UI to exist, initialization can take place each
time you invoke it from the command line. For example, the code in an OpeningFcn will
run each time a GUIDE program runs unless you take steps to prevent it from doing so.
Adding a flag to the handles structure is one way to control such behavior. You can do
this in the OpeningFcn, which can run initialization code if this flag doesn't yet exist
and skip that code if it does.
Note This option is available only if you first select the Generate FIG-file and
MATLAB file option.
Use System Color Scheme for Background
The default color used for UI components is system dependent. This option enables you to
make the figure background color the same as the default component background color.
5-11
To ensure that the figure background matches the color of the components, select Use
system color scheme for background in the GUI Options dialog.
Note This option is available only if you first select the Generate FIG-file and
MATLAB file option.
In this case, GUIDE selects Generate FIG-file only, even when a code file with a
corresponding name exists in the same folder.
Start GUIDE from the command line and provide the name of a FIG-file for which no
code file with the same name exists in the same folder.
guide('myfig.fig')
Use the GUIDE Open Existing GUI tab to open a FIG-file for which no code file
with the same name exists in the same folder.
When you save the figure or UI with Generate FIG-file only selected, GUIDE saves
only the FIG-file. You must update any corresponding code files yourself, as appropriate.
If you want GUIDE to manage the UI code file for you, change the selection to Generate
FIG-file and MATLAB file before saving the UI. If there is no corresponding code file in
the same location, GUIDE creates one. If a code file with the same name as the original
figure or UI exists in the same folder, GUIDE overwrites it. To prevent overwriting an
existing file, save the UI using Save As from the File menu. Select another file name for
the two files. GUIDE updates variable names in the new code file as appropriate.
5-12
GUIDE Options
Any file that a callback executes must be in the current folder or on the MATLAB path.
For more information on how callbacks work, see Write Callbacks in GUIDE on page
7-2
More About
5-13
6
Lay Out a UI Using GUIDE
GUIDE Templates on page 6-2
Set the UI Window Size in GUIDE on page 6-11
Add Components to the GUIDE Layout Area on page 6-13
Align GUIDE UI Components on page 6-65
Customize Tabbing Behavior in a GUIDE UI on page 6-74
Create Menus for GUIDE UIs on page 6-77
Create Toolbars for GUIDE UIs on page 6-94
Design Cross-Platform UIs in GUIDE on page 6-106
GUIDE Templates
In this section...
Access the Templates on page 6-2
Template Descriptions on page 6-3
6-2
GUIDE Templates
To use a template:
1
Select a template in the left pane. A preview displays in the right pane.
Optionally, name your UI now by selecting Save new figure as and typing the
name in the field to the right. GUIDE saves the UI before opening it in the Layout
Editor. If you choose not to name the UI at this point, GUIDE prompts you to save it
and give it a name the first time you run your program.
Template Descriptions
GUIDE provides four fully functional templates. They are described in the following
sections:
Blank GUI on page 6-3
GUI with Uicontrols on page 6-4
GUI with Axes and Menu on page 6-6
Modal Question Dialog on page 6-8
Out of the box, none of the UI templates include a menu bar or a toolbar. Neither can
they dock in the MATLAB desktop. You can, however, override these GUIDE defaults to
provide and customize these controls. See the sections Create Menus for GUIDE UIs on
page 6-77 and Create Toolbars for GUIDE UIs on page 6-94 for details.
Note To see how the templates work, you can view their code and look at their callbacks.
You can also modify the callbacks for your own purposes. To view the code file for any of
these templates, open the template in the Layout Editor and click the Editor button
on the toolbar.
Blank GUI
The following figure shows an example of this template.
6-3
Select this template when the other templates are not suitable for the UI you want to
create.
GUI with Uicontrols
The following figure shows an example of this template. The user interface controls
shown in this template are the push buttons, radio buttons, edit text, and static text.
6-4
GUIDE Templates
When you click the Run button , the UI appears as shown in the following figure.
6-5
When you enter values for the density and volume of an object, and click the Calculate
button, the program calculates the mass of the object and displays the result next to
Mass(D*V).
To view the code for these user interface controls, open the template in the Layout Editor
and click the Editor button on the toolbar.
GUI with Axes and Menu
The following figure shows an example of this template.
6-6
GUIDE Templates
When you click the Run button on the toolbar, the UI displays a plot of five lines, each
of which is generated from random numbers using the MATLAB rand(5) command. The
following figure shows an example.
6-7
You can select other plots in the pop-up menu. Clicking the Update button displays the
currently selected plot on the axes.
The UI also has a File menu with three items:
Open displays a dialog box from which you can open files on your computer.
Print opens the Print dialog box. Clicking OK in the Print dialog box prints the
figure.
Close closes the UI.
To view the code for these menu choices, open the template in the Layout Editor and click
the Editor button on the toolbar.
Modal Question Dialog
The following figure shows an example of this template.
6-8
GUIDE Templates
When you click the Run button, the following dialog displays.
6-9
The dialog returns the text string, Yes or No, depending on which button you click.
Select this template if you want your UI to return a string or to be modal.
Modal dialogs are blocking, which means that the code stops executing while dialog
exists. This means that the user cannot interact with other MATLAB windows until they
click one of the dialog buttons.
To view the code for this dialog, open the template in the Layout Editor and click the
Editor button on the toolbar.
Related Examples
More About
6-10
As you drag the corner handle, the readout in the lower right corner shows the current
position of the UI in pixels.
Note Setting the Units property to characters (nonresizable UIs) or normalized
(resizable UIs) gives the UI a more consistent appearance across platforms. See CrossPlatform Compatible Units on page 6-107 for more information.
Set each objects Units property to an absolute value, such as inches or pixels before
enlarging the UI.
To change the Units property for all the objects in your UI simultaneously, drag a
selection box around all the objects, and then click the Property Inspector button
and set the Units.
When you finish enlarging the UI, set each objects Units property back to
normalized.
6-11
In the Layout Editor, open the Property Inspector for the figure by clicking the
button (with no components selected).
In the Property Inspector, scroll to the Units property and note whether the current
setting is characters or normalized.
Click the down arrow at the far right in the Units row, and select inches.
In the Property Inspector, display the Position property elements by clicking the +
sign to the left of Position.
Change the x and y coordinates to the point where you want the lower-left corner of
the window to appear, and its width and height.
Select File > Preferences, and then clear Show names in component palette
Related Examples
More About
6-12
Place Components
The component palette at the left side of the Layout Editor contains the components that
you can add to your UI.
Note See Create Menus for GUIDE UIs on page 6-77 for information about adding
menus to a UI. See Create Toolbars for GUIDE UIs on page 6-94 for information
about working with the toolbar.
To place components in the GUIDE layout area and give each component a unique
identifier, follow these steps:
1
Once you have defined a UI component in the layout area, selecting it automatically
shows it in the Property Inspector. If the Property Inspector is not open or is not
visible, double-clicking a component raises the inspector and focuses it on that
component.
The components listed in the following table have additional considerations; read
more about them in the sections described there.
If You Are Adding...
Then...
Menus
Toolbars
ActiveX controls
See Grid and Rulers on page 6-71 for information about using the grid.
3
Assign a unique identifier to each component. Do this by setting the value of the
component Tag properties. SeeAssign an Identifier to Each Component on page
6-19 for more information.
Specify the look and feel of each component by setting the appropriate properties.
The following topics contain specific information.
User Interface Controls on page 6-19
Panels and Button Groups on page 6-40
Axes on page 6-45
Table on page 6-49
ActiveX Component on page 6-60
This is an example of a UI in the Layout Editor. Components in the Layout Editor are
not active.
6-14
The Position values updates as you move and resize components. The first two
elements in the vector change as you move the component. The last two elements of
the vector change as the height and width of the component change.
When no components are selected, the Position value displays the location and size
of the figure.
Add a Component to a Panel or Button Group
To add a component to a panel or button group, select the component in the component
palette then move the cursor over the desired panel or button group. The position of the
cursor determines the component's parent.
GUIDE highlights the potential parent as shown in the following figure. The highlight
indicates that if you drop the component or click the cursor, the component will be a child
of the highlighted panel, button group, or figure.
6-16
Note Assign a unique identifier to each component in your panel or button group by
setting the value of its Tag property. See Assign an Identifier to Each Component on
page 6-19 for more information.
6-17
When you add a new component or drag an existing component to a panel or button
group, it will become a member, or child, of the panel or button group automatically,
whether fully or partially enclosed by it. However, if the component is not entirely
contained in the panel or button group, it appears to be clipped in the Layout Editor.
When you run the program, the entire component is displayed and straddles the panel
or button group border. The component is nevertheless a child of the panel and behaves
accordingly. You can use the Object Browser to determine the child objects of a panel or
button group.
You can add a new panel or button group to a UI in order to group any of its existing
controls. In order to include such controls in a new panel or button group, do the
following. The instructions refer to panels, but you do the same for components inside
button groups.
1
Select the New Panel or New Button Group tool and drag out a rectangle to have the
size and position you want.
The panel will not obscure any controls within its boundary unless they are axes,
tables, or other panels or button groups. Only overlap panels you want to nest, and
then make sure the overlap is complete.
You can use Send Backward or Send to Back on the Layout menu to layer the
new panel behind components you do not want it to obscure, if your layout has this
problem. As you add components to it or drag components into it, the panel will
automatically layer itself behind them.
Now is a good time to set the panel's Tag and String properties to whatever you
want them to be, using the Property Inspector.
Open the Object Browser from the View menu and find the panel you just added.
Use this tool to verify that it contains all the controls you intend it to group together.
If any are missing, perform the following steps.
Drag controls that you want to include but don't fit within the panel inside it to
positions you want them to have. Also, slightly move controls that are already in
their correct positions to group them with the panel.
The panel highlights when you move a control, indicating it now contains the control.
The Object Browser updates to confirm the relationship. If you now move the panel,
its child controls move with it.
6-18
Tip You need to move controls with the mouse to register them with the surrounding
panel or button group, even if only by a pixel or two. Selecting them and using arrow
keys to move them does not accomplish this. Use the Object Browser to verify that
controls are properly nested.
See Panels and Button Groups on page 6-40 for more information on how to
incorporate panels and button groups into a UI.
Assign an Identifier to Each Component
Use the Tag property to assign each component a unique meaningful string identifier.
When you place a component in the layout area, GUIDE assigns a default value to the
Tag property. Before saving the UI, replace this value with a string that reflects the role
of the component in the UI.
The string value you assign Tag is used by code to identify the component and must be
unique in the UI. To set Tag:
1
Select View > Property Inspector or click the Property Inspector button
In the layout area, select the component for which you want to set Tag.
In the Property Inspector, select Tag and then replace the value with the string you
want to use as the identifier. In the following figure, Tag is set to mybutton.
6-19
To define user interface controls, you must set certain properties. To do this:
1
Use the Property Inspector to modify the appropriate properties. Open the Property
Inspector by selecting View > Property Inspector or by clicking the Property
Inspector button
Subsequent topics describe commonly used properties of user interface controls and offer
a simple example for each kind of control:
Commonly Used Properties on page 6-20
Push Button on page 6-21
Slider on page 6-23
Radio Button on page 6-24
Check Box on page 6-26
Edit Text on page 6-28
Static Text on page 6-30
Pop-Up Menu on page 6-31
List Box on page 6-34
Toggle Button on page 6-37
Commonly Used Properties
The most commonly used properties needed to describe a user interface control are shown
in the following table. Instructions for a particular control may also list properties that
are specific to that control.
6-20
Property
Value
Description
Enable
Max
Scalar. Default is 1.
Maximum value.
Interpretation depends on the
type of component.
Min
Scalar. Default is 0.
Minimum value.
Interpretation depends on the
type of component.
Property
Value
Description
Position
String
Units
Value
Scalar or vector
For a complete list of properties and for more information about the properties listed in
the table, see Uicontrol Properties.
Push Button
To create a push button with label Button 1, as shown in this figure:
6-21
Specify the push button label by setting the String property to the desired label, in
this case, Button 1.
To display the & character in a label, use two & characters in the string. The words
remove, default, and factory (case sensitive) are reserved. To use one of these as a
label, prepend a backslash (\) to the string. For example, \remove yields remove.
The push button accommodates only a single line of text. If you specify more than
one line, only the first line is shown. If you create a push button that is too narrow to
accommodate the specified String, MATLAB software truncates the string with an
ellipsis.
If you want to set the position or size of the component to an exact value, then modify
its Position property.
To add an image to a push button, assign the button's CData property as an mby-n-by-3 array of RGB values that defines a truecolor image. You must do this
programmatically in the opening function of the UI code file. For example, the array
img defines a 16-by-64-by-3 truecolor image using random values between 0 and 1
(generated by rand).
img = rand(16,64,3);
set(handles.pushbutton1,'CData',img);
Specify the range of the slider by setting its Min property to the minimum value of
the slider and its Max property to the maximum value. The Min property must be less
than Max.
Specify the value indicated by the slider when it is created by setting the Value
property to the appropriate number. This number must be less than or equal to Max
and greater than or equal to Min. If you specify Value outside the specified range, the
slider is not displayed.
The slider Value changes by a small amount when a user clicks the arrow button,
and changes by a larger amount when the user clicks the trough (also called
the channel). Control how the slider responds to these actions by setting the
6-23
If you want to set the location or size of the component to an exact value, then modify
its Position property.
The slider component provides no text description or data entry capability. Use a
Static Text on page 6-30 component to label the slider. Use an Edit Text on
page 6-28 component to enable a user to input a value to apply to the slider.
Note: On Mac platforms, the height of a horizontal slider is constrained. If the height
you set in the position vector exceeds this constraint, the displayed height of the slider
is the maximum allowed. The height element of the position vector is not changed.
Radio Button
To create a radio button with label Indent nested functions, as shown in this figure:
6-24
Specify the radio button label by setting the String property to the desired label, in
this case, Indent nested functions.
To display the & character in a label, use two & characters in the string. The words
remove, default, and factory (case sensitive) are reserved. To use one of these as a
label, prepend a backslash (\) to the string. For example, \remove yields remove.
The radio button accommodates only a single line of text. If you specify more than
one line, only the first line is shown. If you create a radio button that is too narrow to
accommodate the specified String, MATLAB software truncates the string with an
ellipsis.
Create the radio button with the button selected by setting its Value property to the
value of its Max property (default is 1). Set Value to Min (default is 0) to leave the
radio button unselected. Correspondingly, when the user selects the radio button, the
software sets Value to Max, and to Min when the user deselects it.
6-25
If you want to set the position or size of the component to an exact value, then modify
its Position property.
To add an image to a radio button, assign the button's CData property an mby-n-by-3 array of RGB values that defines a truecolor image. You must do this
programmatically in the opening function of the UI code file. For example, the array
img defines a 16-by-24-by-3 truecolor image using random values between 0 and 1
(generated by rand).
img = rand(16,24,3);
set(handles.radiobutton1,'CData',img);
Note To manage exclusive selection of radio buttons and toggle buttons, put them in a
button group. See Button Group on page 6-43 for more information.
Check Box
To create a check box with label Display file extension that is initially checked, as
shown in this figure:
Specify the check box label by setting the String property to the desired label, in this
case, Display file extension.
6-26
To display the & character in a label, use two & characters in the string. The words
remove, default, and factory (case sensitive) are reserved. To use one of these as a
label, prepend a backslash (\) to the string. For example, \remove yields remove.
The check box accommodates only a single line of text. If you specify a component
width that is too small to accommodate the specified String, MATLAB software
truncates the string with an ellipsis.
Create the check box with the box checked by setting the Value property to the value
of the Max property (default is 1). Set Value to Min (default is 0) to leave the box
unchecked. Correspondingly, when the user clicks the check box, the software sets
Value to Max when the user checks the box and to Min when the user clears it.
If you want to set the position or size of the component to an exact value, then modify
its Position property.
6-27
Edit Text
To create an edit text component that displays the initial text Enter your name here,
as shown in this figure:
Specify the text to be displayed when the edit text component is created by setting the
String property to the desired string, in this case, Enter your name here.
To display the & character in a label, use two & characters in the string. The words
remove, default, and factory (case sensitive) are reserved. To use one of these as a
label, prepend a backslash (\) to the string. For example, \remove yields remove.
To enable multiple-line input, specify the Max and Min properties so that their
difference is greater than 1. For example, Max = 2, Min = 0. Max default is1, Min
default is 0. MATLAB software wraps the string and adds a scroll bar if necessary. On
all platforms, when the user enters a multiline text box via the Tab key, the editing
cursor is placed at its previous location and no text highlights.
6-28
If Max-Min is less than or equal to 1, the edit text component admits only a single
line of input. If you specify a component width that is too small to accommodate the
specified string, MATLAB software displays only part of the string. The user can
use the arrow keys to move the cursor through the entire string. On all platforms,
when the user enters a single-line text box via the Tab key, the entire contents is
highlighted and the editing cursor is at the end (right side) of the string.
If you want to set the position or size of the component to an exact value, then modify
its Position property.
You specify the text font to display in the edit box by typing the name of a font
residing on your system into the FontName entry in the Property Inspector. On
6-29
Specify the text that appears in the component by setting the component String
property to the desired text, in this case Select a data set.
6-30
To display the & character in a list item, use two & characters in the string. The
words remove, default, and factory (case sensitive) are reserved. To use one of
these as a label, prepend a backslash (\) to the string. For example, \remove yields
remove.
If your component is not wide enough to accommodate the specified String,
MATLAB software wraps the string.
If you want to set the position or size of the component to an exact value, then modify
its Position property.
You can specify a text font, including its FontName, FontWeight, FontAngle,
FontSize, and FontUnits properties. For details, see the previous topic, Edit Text
on page 6-28, and for a programmatic approach, the section How to Set Font
Characteristics on page 9-25.
Pop-Up Menu
To create a pop-up menu (also known as a drop-down menu or combo box) with items
one, two, three, and four, as shown in this figure:
6-31
Specify the pop-up menu items to be displayed by setting the String property to the
desired items. Click the
button to the right of the property name to open the Property Inspector editor.
6-32
To display the & character in a menu item, use two & characters in the string. The
words remove, default, and factory (case sensitive) are reserved. To use one of
these as a label, prepend a backslash (\) to the string. For example, \remove yields
remove.
If the width of the component is too small to accommodate one or more of the specified
strings, MATLAB software truncates those strings with an ellipsis.
To select an item when the component is created, set Value to a scalar that indicates
the index of the selected list item, where 1 corresponds to the first item in the list. If
you set Value to 2, the menu looks like this when it is created:
6-33
If you want to set the position and size of the component to exact values, then modify
its Position property. The height of a pop-up menu is determined by the font size.
The height you set in the position vector is ignored.
Note The pop-up menu does not provide for a label. Use a Static Text on page
6-30 component to label the pop-up menu.
List Box
To create a list box with items one, two, three, and four, as shown in this figure:
6-34
Specify the list of items to be displayed by setting the String property to the desired
list. Use the Property Inspector editor to enter the list. You can open the editor by
clicking the
6-35
To display the & character in a label, use two & characters in the string. The words
remove, default, and factory (case sensitive) are reserved. To use one of these as a
label, prepend a backslash (\) to the string. For example, \remove yields remove.
If the width of the component is too small to accommodate one or more of the specified
strings, MATLAB software truncates those strings with an ellipsis.
Specify selection by using the Value property together with the Max and Min
properties.
To select a single item when the component is created, set Value to a scalar that
indicates the index of the selected list item, where 1 corresponds to the first item
in the list.
To select more than one item when the component is created, set Value to a vector
of indices of the selected items. Value = [1,3] results in the following selection.
6-36
To enable selection of more than one item, you must specify the Max and Min
properties so that their difference is greater than 1. For example, Max = 2, Min
= 0. Max default is1, Min default is 0.
If you want no initial selection, set the Max and Min properties to enable multiple
selection, i.e., Max - Min > 1, and then set the Value property to an empty
matrix [].
If the list box is not large enough to display all list entries, you can set the
ListBoxTop property to the index of the item you want to appear at the top when the
component is created.
If you want to set the position or size of the component to an exact value, then modify
its Position property.
Note The list box does not provide for a label. Use a Static Text on page 6-30
component to label the list box.
Toggle Button
To create a toggle button with label Left/Right Tile, as shown in this figure:
6-37
Specify the toggle button label by setting its String property to the desired label, in
this case, Left/Right Tile.
To display the & character in a label, use two & characters in the string. The words
remove, default, and factory (case sensitive) are reserved. To use one of these as a
label, prepend a backslash (\) to the string. For example, \remove yields remove.
The toggle button accommodates only a single line of text. If you specify more than
one line, only the first line is shown. If you create a toggle button that is too narrow to
accommodate the specified String, MATLAB software truncates the string with an
ellipsis.
6-38
Create the toggle button with the button selected (depressed) by setting its Value
property to the value of its Max property (default is 1). Set Value to Min (default is 0)
to leave the toggle button unselected (raised). Correspondingly, when the user selects
the toggle button, MATLAB software sets Value to Max, and to Min when the user
deselects it. The following figure shows the toggle button in the depressed position.
If you want to set the position or size of the component to an exact value, then modify
its Position property.
To add an image to a toggle button, assign the button's CData property an mby-n-by-3 array of RGB values that defines a truecolor image. You must do this
programmatically in the opening function of the UI code file. For example, the array
img defines a 16-by-64-by-3 truecolor image using random values between 0 and 1
(generated by rand).
img = rand(16,64,3);
set(handles.togglebutton1,'CData',img);
Note To manage exclusive selection of radio buttons and toggle buttons, put them in a
button group. See Button Group on page 6-43 for more information.
6-39
Use the Property Inspector to modify the appropriate properties. Open the Property
Inspector by selecting View > Property Inspector or by clicking the Property
Inspector button .
Subsequent topics describe commonly used properties of panels and button groups and
offer a simple example for each component.
Commonly Used Properties on page 6-40
Panel on page 6-41
Button Group on page 6-43
Commonly Used Properties
The most commonly used properties needed to describe a panel or button group are
shown in the following table:
6-40
Property
Values
Description
Position
Title
String
Component label.
TitlePosition
lefttop, centertop,
righttop, leftbottom,
centerbottom,
rightbottom. Default is
lefttop.
Units
characters,
centimeters, inches,
normalized, pixels,
Property
Values
points. Default is
characters.
Description
For a complete list of properties and for more information about the properties listed in
the table, see the Uipanel Properties and Uibuttongroup Properties.
Panel
To create a panel with title My Panel as shown in the following figure:
Specify the panel title by setting the Title property to the desired string, in this case
My Panel.
6-41
To display the & character in the title, use two & characters in the string. The words
remove, default, and factory (case sensitive) are reserved. To use one of these as a
label, prepend a backslash (\) to the string. For example, \remove yields remove.
Specify the location of the panel title by selecting one of the available
TitlePosition property values from the pop-up menu, in this case lefttop. You
can position the title at the left, middle, or right of the top or bottom of the panel.
6-42
If you want to set the position or size of the panel to an exact value, then modify its
Position property.
Button Group
To create a button group with title My Button Group as shown in the following figure:
6-43
Specify the button group title by setting the Title property to the desired string, in
this case My Button Group.
6-44
To display the & character in the title, use two & characters in the string. The words
remove, default, and factory (case sensitive) are reserved. To use one of these as a
label, prepend a backslash (\) to the string. For example, \remove yields remove.
Specify the location of the button group title by selecting one of the available
TitlePosition property values from the pop-up menu, in this case lefttop. You
can position the title at the left, middle, or right of the top or bottom of the button
group.
If you want to set the position or size of the button group to an exact value, then
modify its Position property.
Axes
Axes enable your UI to display graphics such as graphs and images using commands
such as: plot, surf, line, bar, polar, pie, contour, and mesh.
To define an axes, you must set certain properties. To do this:
6-45
Use the Property Inspector to modify the appropriate properties. Open the Property
Inspector by selecting View > Property Inspector or by clicking the Property
Inspector button .
Subsequent topics describe commonly used properties of axes and offer a simple example.
Commonly Used Properties on page 6-46
Create Axes on page 6-47
Commonly Used Properties
The most commonly used properties needed to describe an axes are shown in the
following table:
Property
Values
Description
NextPlot
add, replace,
Specifies whether plotting
replacechildren. Default adds graphics, replaces
graphics and resets axes
is replace
properties to default, or
replaces graphics only.
Position
Units
normalized,
Units of measurement used
to interpret position vector
centimeters,
characters, inches,
pixels, points. Default is
normalized.
For a complete list of properties and for more information about the properties listed in
the table, see Axes Properties.
See commands such as the following for more information on axes objects: plot, surf,
line, bar, polar, pie, contour, imagesc, and mesh.
Many of these graphing functions reset axes properties by default, according to the
setting of its NextPlot property, which can cause unwanted behavior in a UI, such as
resetting axis limits and removing axes context menus and callbacks. See Create Axes
6-46
on page 6-47 and Axes on page 9-23 for information about setting the NextPlot
property.
Create Axes
Here is an axes in a GUIDE UI:
6-47
Use the title, xlabel, ylabel, zlabel, and text functions in the UI code file to
label an axes component. For example,
xlh = (axes_handle,'Years')
labels the X-axis as Years. The handle of the X-axis label is xlh.
The words remove, default, and factory (case sensitive) are reserved. To use
one of these in component text, prepend a backslash (\) to the string. For example,
\remove yields remove.
If you want to set the position or size of the axes to an exact value, then modify its
Position property.
6-48
If you customize axes properties, some of them (or example, callbacks, font
characteristics, and axis limits and ticks) may get reset to default every time you
draw a graph into the axes when the NextPlot property has its default value of
'replace'. To keep customized properties as you want them, set NextPlot to
'replacechildren' in the Property Inspector, as shown here.
Table
Tables enable you to display data in a two dimensional table. You can use the Property
Inspector to get and set the object property values.
Commonly Used Properties
The most commonly used properties of a table component are listed in the table below.
These are grouped in the order they appear in the Table Property Editor. Please refer to
uitable documentation for detail of all the table properties:
6-49
Group
Property
Values
Column
ColumnName
ColumnFormat
Determines display
and editability of
columns
ColumnWidth
Width of each
column in pixels;
individual column
widths can also be
set to 'auto'
ColumnEditable
Row
RowName
Color
BackgroundColor
n-by-3 matrix of
RGB triples
Background color of
cells
RowStriping
{on} | off
Color striping of
table rows
Data
Table data.
Data
Create a Table
To create a UI with a table in GUIDE as shown, do the following:
6-50
Description
Drag the table icon on to the Layout Editor and right click in the table. From the tables
context menu, select Table Property Editor. You can also select Table Property
Editor from the Tools menu when you select a table by itself.
6-51
When you open it this way, the Table Property Editor displays the Column pane. You
can also open it from the Property Inspector by clicking one of its Table Property Editor
icons
, in which case the Table Property Editor opens to display the pane appropriate
for the property you clicked.
Clicking items in the list on the left hand side of the Table Property Editor changes the
contents of the pane to the right . Use the items to activate controls for specifying the
table's Columns, Rows, Data, and Color options.
The Columns and Rows panes each have a data entry area where you can type names
and set properties. on a per-column or per-row basis. You can edit only one row or column
6-52
definition at a time. These panes contain a vertical group of five buttons for editing and
navigating:
Button
Purpose
Accelerator Keys
Windows
Macintosh
Insert
Insert
Insert
Delete
Ctrl+D
Cmd+D
Copy
Ctrl+P
Cmd+P
Up
Ctrl+
uparrow
Cmd+
uparrow
Down
Ctrl+
downarrow
Cmd+
downarrow
Keyboard equivalents only operate when the cursor is in the data entry area. In addition
to those listed above, typing Ctrl+T or Cmd+T selects the entire field containing the
cursor for editing (if the field contains text).
To save changes to the table you make in the Table Property Editor, click OK, or click
Apply commit changes and keep on using the Table Property Editor.
Set Column Properties
6-53
Select Show names entered below as the column headers and set the ColumnName
by entering Rate, Amount, Available, and Fixed/Adj in Name group. for the Available
and Fixed/Adj columns set the ColumnEditable property to on. Lastly set the
ColumnFormat for the four columns
6-54
For the Rate column, select Numeric. For the Amount Column select Custom and in the
Custom Format Editor, choose Bank.
6-55
Leave the Available column at the default value. This allows MATLAB to chose based
on the value of the Data property of the table. For the Fixed/Adj column select Choice
List to create a pop-up menu. In the Choice List Editor, click Insert to add a second
choice and type Fixed and Adjustable as the 2 choices.
6-56
Note: For a user to select items from a choice list, the ColumnEditable property of the
column that the list occupies must be set to 'true'. The pop-up control only appears
when the column is editable.
Set Row Properties
In the Row tab, leave the default RowName, Show numbered row headers.
6-57
Use the Data property to specify the data in the table. Create the data in the command
window before you specify it in GUIDE. For this example, type:
dat =
6.75,
7,
In the Table Property Editor, select the data that you defined and select Change data
value to the selected workspace variable below.
6-58
Specify the BackgroundColor and RowStriping for your table in the Color tab.
6-59
You can change other uitable properties to the table via the Property Inspector.
ActiveX Component
When you drag an ActiveX component from the component palette into the layout area,
GUIDE opens a dialog box, similar to the following, that lists the registered ActiveX
controls on your system.
Note If MATLAB software is not installed locally on your computer for example, if
you are running the software over a network you might not find the ActiveX control
described in this example. To register the control, see Registering Controls and Servers.
6-60
Select the desired ActiveX control. The right panel shows a preview of the selected
control.
Click Create. The control appears as a small box in the Layout Editor.
Resize the control to approximately the size of the square shown in the preview pane.
You can do this by clicking and dragging a corner of the control, as shown in the
following figure.
6-61
When you select an ActiveX control, you can open the ActiveX Property Editor by rightclicking and selecting ActiveX Property Editor from the context menu or clicking the
Tools menu and selecting it from there.
Note: What an ActiveX Property Editor contains and looks like is dependent on what
user controls that the authors of the particular ActiveX object have created and stored in
the UI for the object. In some cases, a UI without controls or no UI at all appears when
you select this menu item.
6-62
In the Property Inspector, scroll to the Units property and note whether the current
setting is characters or normalized. Click the button next to Units and then
change the setting to inches from the pop-up menu.
6-63
Click the + sign next to Position. The Property Inspector displays the elements of
the Position property.
Type the width and height you want the components to be.
Note To select multiple components, they must have the same parent. That is, they must
be contained in the same figure, panel, or button group. Setting the Units property to
characters (nonresizable UIs) or normalized (resizable UIs) gives the UI a more
consistent appearance across platforms.
Related Examples
More About
6-64
6-65
6-66
All of the align options (vertical top, center, bottom and horizontal left, center, right)
place the selected components with respect to the corresponding edge (or center) of this
bounding box.
Distribute Options
Distributing components adds equal space between all components in the selected group.
The distribute options operate in two different modes:
Default behavior MATLAB distributes space equally among components within the
bounding box.
Select the Set spacing check box You specify the number of pixels between each
component.
Both modes enable you to specify how the spacing is measured, as indicated by the
button labels on the alignment tool. These options include spacing measured with respect
to the following edges:
Vertical inner, top, center, and bottom
Horizontal inner, left, center, and right
6-67
Property Inspector
About the Property Inspector
In GUIDE, as in MATLAB generally, you can see and set most components' properties
using the Property Inspector. To open it from the GUIDE Layout Editor, do any of the
following:
Select the component you want to inspect, or double-click it to open the Property
Inspector and bring it to the foreground
Select View > Property Inspector.
Click the Property Inspector button
The Property Inspector window opens, displaying the properties of the selected
component. For example, here is a view of a push button's properties.
6-68
Scroll down to see additional properties. Click any property value or icon to set its value.
The Property Inspector provides context-sensitive help for individual properties. To see
a definition of any property, right-click the name or value in the Property Inspector and
click the What's This? menu item that appears. A context-sensitive help window opens
displaying the definition of the property.
6-69
6-70
Select View > Property Inspector or click the Property Inspector button
In the Property Inspector, scroll to the Units property and note its current setting,
then change the setting to inches.
Scroll to the Position property. This figure shows the Position property for
multiple components of the same size.
Change the value of x to align their left sides. Change the value of y to align their
bottom edges. For example, setting x to 2.0 aligns the left sides of the components 2
inches from the left side of the window.
When the components are aligned, change the Units property back to its original
setting.
6-71
You can optionally enable snap-to-grid, which causes any object that is moved close to a
grid line to jump to that line. Snap-to-grid works with or without a visible grid.
Use the Grid and Rulers dialog (select Tools > Grid and Rulers) to:
Control visibility of rulers, grid, and guide lines
Set the grid spacing
Enable or disable snap-to-grid
Guide Lines
The Layout Editor has both vertical and horizontal snap-to guide lines. Components snap
to the line when you move them close to the line.
Guide lines are useful when you want to establish a reference for component alignment
at an arbitrary location in the Layout Editor.
Creating Guide Lines
To create a guide line, click the top or left ruler and drag the line into the layout area.
6-72
More About
6-73
6-74
To examine and change the tab order of the panel components, click the panel
background to select it, then select Tools > Tab Order Editor in the Layout Editor.
6-75
The Tab Order Editor displays the panel's components in their current tab order. To
change the tab order, select a component and press the up or down arrow to move the
component up or down in the list. If you set the tab order for the first three components
in the example to be
1
the user first tabs to the Surf push button, then to the Contour push button, and then
to the Mesh push button. Subsequent tabs sequence through the remaining components
at the figure level.
6-76
Figure windows with a standard menu bar also have a Desktop menu from which the
user can dock and undock them.
To display the docking arrow and the Desktop > Dock Figure menu item, use the
Property Inspector to set the figure property DockControls to 'on'. You must also set
the MenuBar and/or ToolBar figure properties to 'figure' to display docking controls.
The WindowStyle figure property also affects docking behavior. The default is
'normal', but if you change it to 'docked', then the following applies:
The UI window opens docked in the desktop when you run it.
6-78
The DockControls property is set to 'on' and cannot be turned off until
WindowStyle is no longer set to 'docked'.
If you undock a UI window created with WindowStyle 'docked', it will have not
have a docking arrow unless the figure displays a menu bar or a toolbar (either
standard or customized). When it has no docking arrow, users can undock it from the
desktop, but will be unable to redock it there.
However, when you provide your own menu bar or toolbar using GUIDE, it can display
the docking arrow if you want the UI window to be dockable. See the following sections
and Create Toolbars for GUIDE UIs on page 6-94 for details.
Note: UIs that are modal dialogs (figures with WindowStyle set to 'modal') cannot
have menu bars, toolbars, or docking controls.
For more information, see the DockControls, MenuBar, ToolBar, and WindowStyle
property descriptions in Figure Properties.
Add Standard Menus to the Menu Bar
The figure MenuBar property controls whether your UI displays the MATLAB standard
menus on the menu bar. GUIDE initially sets the value of MenuBar to none. If you want
your UI to display the MATLAB standard menus, use the Property Inspector to set
MenuBar to figure.
If the value of MenuBar is none, GUIDE automatically adds a menu bar that displays
only the menus you create.
If the value of MenuBar is figure, the UI displays the MATLAB standard menus and
GUIDE adds the menus you create to the right side of the menu bar.
In either case, you can enable the user to dock and undock the window by setting the
figure's DockControls property to 'on'.
Create a Menu
1
Start a new menu by clicking the New Menu button in the toolbar. A menu title,
Untitled 1, appears in the left pane of the dialog box.
6-79
Note By default, GUIDE selects the Menu Bar tab when you open the Menu Editor.
2
6-80
Click the menu title to display a selection of menu properties in the right pane.
Fill in the Label and Tag fields for the menu. For example, set Label to File and
set Tag to file_menu. Click outside the field for the change to take effect.
Label is a string that specifies the text label for the menu item. To display the &
character in a label, use two & characters in the string. The words remove, default,
and factory (case sensitive) are reserved. To use one of these as labels, prepend a
backslash (\) to the string. For example, \remove yields remove.
Tag is a string that is an identifier for the menu object. It is used in the code to
identify the menu item and must be unique in your UI code file.
6-81
6-82
Add an Open menu item under File, by selecting File then clicking the New
Menu Item button in the toolbar. A temporary numbered menu item label,
Untitled, appears.
Fill in the Label and Tag fields for the new menu item. For example, set Label to
Open and set Tag to menu_file_open. Click outside the field for the change to take
effect.
6-83
Specify a string for the routine, i.e., the Callback, that performs the action
associated with the menu item. If you have not yet saved the UI, the default value is
%automatic. When you save the UI, and if you have not changed this field, GUIDE
automatically sets the value using a combination of the Tag field and the UI file
name. See Menu Item on page 7-23 for more information about specifying this
field and for programming menu items.
The View button displays the callback, if there is one, in an editor. If you have not yet
saved the UI, GUIDE prompts you to save it.
Open the Property Inspector, where you can change all menu properties, by clicking
the More Properties button. For detailed information about the properties, see
Uimenu Properties.
Note See Menu Item on page 7-23 and How to Update a Menu Item Check on
page 7-25 for programming information and basic examples.
Additional Drop-Down Menus
To create additional drop-down menus, use the New Menu button in the same way you
did to create the File menu. For example, the following figure also shows an Edit dropdown menu.
Cascading Menus
To create a cascading menu, select the menu item that will be the title for the cascading
menu, then click the New Menu Item button. In the example below, Copy is a cascading
menu.
6-84
Note See Menu Item on page 7-23 for information about programming menu items.
The following Menu Editor illustration shows three menus defined for the figure menu
bar.
6-85
When you run your program, the menu titles appear in the menu bar.
6-86
Context Menus
A context menu is displayed when a user right-clicks the object for which the menu is
defined. The Menu Editor enables you to define context menus and associate them with
objects in the layout. The process has three steps:
1
2
3
Note See Menus for the Menu Bar on page 6-77 for information about defining menus
in general. See Menu Item on page 7-23 for information about defining local
callback functions for your menus.
6-87
6-88
Select the Menu Editor's Context Menus tab and select the New Context Menu
button from the toolbar.
Select the menu, and in the Tag field type the context menu tag
(axes_context_menu in this example).
6-89
6-90
Fill in the Label and Tag fields for the new menu item. For example, set Label to
Blue background color and set Tag to blue_background. Click outside the
field for the change to take effect.
6-91
callback in the code file using a combination of the Tag field and the UI file name.
The callback's name does not display in the Callback field of the Menu Editor, but
selecting the menu item does trigger it.
You can also type an unquoted string into the Callback field to serve as a callback. It
can be any valid MATLAB expression or command. For example, the string
set(gca, 'Color', 'y')
sets the current axes background color to yellow. However, the preferred approach to
performing this operation is to place the callback in the UI code file. This avoids the
use of gca, which is not always reliable when several figures or axes exist. Here is a
version of this callback coded as a function in the UI code file:
function axesyellow_Callback(hObject, eventdata, handles)
% hObject
handle to axesyellow (see GCBO)
% eventdata reserved - to be defined in a future version of MATLAB
% handles
structure with handles and user data (see GUIDATA)
set(handles.axes1,'Color','y')
This code sets the background color of the axes with Tag axes1 no matter to what
object the context menu is attached to.
If you enter a callback string in the Menu Editor, it overrides the callback for the item
in the code file, if any has been saved. If you delete a string you have entered in the
Callback field, the callback for the item in the UI code file is executed when the user
selects that item in the UI.
See Menu Item on page 7-23 for more information about specifying this field and
for programming menu items. For another example of programming context menus in
GUIDE, see Synchronized Data Presentations in a GUIDE UI on page 8-17.
The View button displays the callback, if there is one, in an editor. If you have not yet
saved the UI, GUIDE prompts you to save it.
Open the Property Inspector, where you can change all menu properties except
callbacks, by clicking the More Properties button. For detailed information about
these properties, see Uicontextmenu Properties.
Associate the Context Menu with an Object
6-92
In the Layout Editor, select the object for which you are defining the context menu.
Use the Property Inspector to set this object's UIContextMenu property to the name
of the desired context menu.
The following figure shows the UIContextMenu property for the axes object with Tag
property axes1.
In the UI code file, complete the local callback function for each item in the context menu.
Each callback executes when a user selects the associated context menu item. See Menu
Item on page 7-23 for information on defining the syntax.
Note See Menu Item on page 7-23 and How to Update a Menu Item Check on
page 7-25 for programming information and basic examples.
Related Examples
More About
6-93
You can also open the Toolbar Editor from the Tools menu.
6-94
The Toolbar Editor gives you interactive access to all the features of the uitoolbar,
uipushtool, and uitoggletool functions. It only operates in the context of GUIDE;
you cannot use it to modify any of the built-in MATLAB toolbars. However, you can use
the Toolbar Editor to add, modify, and delete a toolbar from any UI in GUIDE.
Currently, you can add one toolbar to your UI in GUIDE. However, your UI can also
include the standard MATLAB figure toolbar. If you need to, you can create a toolbar
that looks like a normal figure toolbar, but customize its callbacks to make tools (such as
pan, zoom, and open) behave in specific ways.
Note: You do not need to use the Toolbar Editor if you simply want your UI to have a
standard figure toolbar. You can do this by setting the figure's ToolBar property to
'figure', as follows:
6-95
6-96
To add a tool, drag an icon from the Tool Palette into the Toolbar Layout (which
initially contains the text prompt shown above), and edit the tool's properties in the Tool
Properties pane.
When you first create a UI, no toolbar exists on it. When you open the Toolbar Editor and
place the first tool, a toolbar is created and a preview of the tool you just added appears
in the top part of the window. If you later open a UI that has a toolbar, the Toolbar
Editor shows the existing toolbar, although the Layout Editor does not.
Add Tools
You can add a tool to a toolbar in three ways:
Drag and drop tools from the Tool Palette.
6-97
6-98
The set of icons on the bottom of the Tool Palette represent standard MATLAB figure
tools. Their behavior is built in. Predefined tools that require an axes (such as pan and
zoom) do not exhibit any behavior in UIs lacking axes. The callback(s) defining the
behavior of the predefined tool are shown as %default, which calls the same function
that the tool calls in standard figure toolbars and menus (to open files, save figures,
change modes, etc.). You can change %default to some other callback to customize the
tool; GUIDE warns you that you will modify the behavior of the tool when you change a
callback field or click the View button next to it, and asks if you want to proceed or not.
Custom Tools
The two icons at the top of the Tool Palette create pushtools and toggletools. These
have no built-in behavior except for managing their appearance when clicked on and
off. Consequently, you need to provide your own callback(s) when you add one to your
toolbar. In order for custom tools to respond to clicks, you need to edit their callbacks to
create the behaviors you desire. Do this by clicking the View button next to the callback
in the Tool Properties pane, and then editing the callback in the Editor window.
Add and Remove Separators
Separators are vertical bars that set off tools, enabling you to group them visually. You
can add or remove a separator in any of three ways:
Right-click on a tool's preview and select Show Separator, which toggles its
separator on and off.
Check or clear the check box Separator to the left in the tool's property pane.
Change the Separator property of the tool from the Property Inspector
After adding a separator, that separator appears in the Toolbar Layout to the left of
the tool. The separator is not a distinct object or icon; it is a property of the tool.
Move Tools
You can reorder tools on the toolbar in two ways:
6-99
context menu. The Icon Editor opens with the tools CData loaded into it. For information
about editing icons, see Use the Icon Editor on page 6-102.
Edit Toolbar Properties
If you click an empty part of the toolbar or click the Toolbar Properties tab, you can
edit two of its properties:
Tag The internal name for the toolbar
Visible Whether the toolbar is displayed in your UI
The Tag property is initially set to uitoolbar1. The Visible property is set to on.
When on, the Visible property causes the toolbar to be displayed on the UI regardless
of the setting of the figures Toolbar property. If you want to toggle a custom toolbar as
you can built-in ones (from the View menu), you can create a menu item, a check box, or
other control to control its Visible property.
To access nearly all the properties for the toolbar in the Property Inspector, click More
Properties.
Test Your Toolbar
To try out your toolbar, click the Run button in the Layout Editor. The software asks if
you want to save changes to its .fig file first.
Remove a Toolbar
You can remove a toolbar completelydestroying itfrom the Toolbar Editor, leaving
your UI without a toolbar (other than the figure toolbar, which is not visible by default).
The are two ways to remove a toolbar:
Right-click a blank area on the toolbar and select Remove Toolbar from the context
menu.
If you remove all the individual tools in the ways shown in Remove Tools on page
6-100 without removing the toolbar itself, your UI will contain an empty toolbar.
Close the Toolbar Editor
You can close the Toolbar Editor window in two ways:
Press the OK button.
6-101
Icon file name The icon image file to be loaded for editing
Import button Opens a file dialog to select an existing icon file for editing
Drawing tools A group of four tools on the left side for editing icons
Pencil tool Color icon pixels by clicking or dragging
Eraser tool Erase pixels to be transparent by clicking or dragging
Paint bucket tool Flood regions of same-color pixels with the current color
Pick color tool Click a pixel or color palette swatch to define the current color
Icon Edit pane A n-by-m grid where you color an icon
Preview pane A button with a preview of current state of the icon
Color Palette Swatches of color that the pencil and paint tools can use
More Colors button Opens the Colors dialog box for choosing and defining colors
OK button Dismisses the dialog and returns the icon in its current state
Cancel button Closes the dialog without returning the icon
To work with the Icon Editor,
1
Click OK to close the dialog and return the icon you created or click Cancel to close
the dialog without modifying the selected tools icon.
6-103
The Toolbar Editor and Icon Editor are shown together below.
Related Examples
6-104
More About
6-105
As an alternative, use the set command to set the property in the UI code file.
For example, if there is a push button in your UI and its handle is stored in the
pushbutton1 field of the handles structure, then the statement
set(handles.pushbutton1,'FontName','default')
using the default figure Units of pixels does not produce a UI that looks the same on
all platforms.
For this reason, GUIDE defaults the Units property for the figure to characters.
System-Dependent Units
Character units are defined by characters from the default system font. The width
of a character unit equals the width of the letter x in the system font. The height of
a character unit is the distance between the baselines of two lines of text. Note that
character units are not square.
Units and Resize Behavior
If you set the resize behavior from the GUI Options dialog box, GUIDE automatically
sets the units for the UI components in a way that maintains the intended look and feel
across platforms. To specify the resize behavior option, select Tools > GUI Options, and
select an item from the Resize behavior pop-up menu:
If you choose Non-resizable, GUIDE defaults the component units to characters.
If you choose Proportional, GUIDE defaults the component units to normalized.
If you choose Other (Use SizeChangedFcn), GUIDE defaults the component
units to characters. However, you must provide a SizeChangedFcn callback to
customize the resize behavior.
The Non-resizable and Proportional options enable your UI to automatically adjust
the size and relative spacing of components when the UI displays on different computers.
Note GUIDE does not automatically adjust component units if you modify the figure's
Resize property programmatically or in the Property Inspector.
At times, it might be convenient to use a more familiar unit of measure, e.g., inches
or centimeters, when you are laying out the UI. However, to preserve the look of your
UI on different computers, remember to change the figure Units property back to
characters, and the components' Units properties to characters (nonresizable UIs)
or normalized (resizable UIs) before you save the UI.
6-108
7
Programming a GUIDE UI
Write Callbacks in GUIDE on page 7-2
Initialize UIs Created Using GUIDE on page 7-8
Callbacks for Specific Components on page 7-12
Examples of GUIDE UIs on page 7-30
Programming a GUIDE UI
Callback
7-2
uicontextmenu, uicontrol,
uimenu
CellEditCallback
End user edits a value in a table
whose cells are editable.
uitable
CellSelectionCallback
End user selects cells in a table.
uitable
ClickedCallback
End user clicks the push tool or
toggle tool with the left mouse
button.
uitoggletool, uipushtool
CloseRequestFcn
The figure closes.
figure
CreateFcn
DeleteFcn
KeyPressFcn
OffCallback
uitoggletool
OnCallback
uitoggletool
figure, uipanel,
uibuttongroup
SelectionChangedFcn
End user selects a different radio
button or toggle button within a
button group.
uibuttongroup
WindowButtonDownFcn
End user presses a mouse button
while the pointer is in the figure
window.
figure
WindowButtonMotionFcn
End user moves the pointer within figure
the figure window.
WindowButtonUpFcn
End user releases a mouse button. figure
WindowKeyPressFcn
End user presses a key while the
pointer is on the figure or any of
its child objects.
figure
7-3
Programming a GUIDE UI
WindowKeyReleaseFcn
End user releases a key while the
pointer is on the figure or any of
its child objects.
figure
WindowScrollWheelFcn
End user turns the mouse wheel
while the pointer is on the figure.
figure
If you save this UI with the name, myui, then GUIDE sets the push buttons Callback
property to the following value:
@(hObject,eventdata)myui('pushbutton1_Callback',hObject,eventdata,guidata(hObject))
clicking on the component in the layout, and selecting an item under View Callbacks in
the context menu.
Component
WindowKeyPressFcn
WindowKeyReleaseFcn
WindowScrollWheel
figure
KeyPressFcn
KeyReleaseFcn
SelectionChangedFcn
uibuttongroup
CellEditCallback
CellSelectionCallback
uitable
7-5
Programming a GUIDE UI
Update the components callback property by changing the first argument passed
to the anonymous function. For example, the original callback property for a push
button might look like this:
@(hObject,eventdata)myui('pushbutton1_Callback',...
hObject,eventdata,guidata(hObject))
In this example, you must change the string, 'pushbutton1_Callback' to the new
function name.
3
Change all other references to the old function name to the new function name in the
UI code file.
Deleting Callbacks
You can delete a callback function when you want to remove or change the function that
executes when the end user performs a specific action. To delete a callback function:
7-6
Search and replace all instances that refer to the callback function in your code.
Open the UI in GUIDE and replace all instances that refer to the callback function
in the Property Inspector.
Related Examples
More About
Anonymous Functions
7-7
Programming a GUIDE UI
Opening Function
The opening function is the first callback in every UI code file. It is executed just before
the UI is made visible to the user, but after all the components have been created, i.e.,
after the components' CreateFcn callbacks, if any, have been run.
You can use the opening function to perform your initialization tasks before the user
has access to the UI. For example, you can use it to create data or to read data from an
external source. MATLAB passes any command-line arguments to the opening function.
Function Naming and Template
GUIDE names the opening function by appending _OpeningFcn to the name of the UI.
This is an example of an opening function template as it might appear in the myui code
file.
% --- Executes just before myui is made visible.
function myui_OpeningFcn(hObject, eventdata, handles, varargin)
% This function has no output args, see OutputFcn.
% hObject
handle to figure
% eventdata reserved - to be defined in a future version of MATLAB
% handles
structure with handles and user data (see GUIDATA)
% varargin
command line arguments to myui (see VARARGIN)
% Choose default command line output for myui
handles.output = hObject;
% Update handles structure
guidata(hObject, handles);
% UIWAIT makes myui wait for user response (see UIRESUME)
% uiwait(handles.myui);
Input Arguments
The opening function has four input arguments hObject, eventdata, handles, and
varargin. The first three are the same as described in GUIDE Callback Syntax
on page 7-5. the last argument, varargin, enables you to pass arguments from the
7-8
command line to the opening function. The opening function can take actions with
them (for example, setting property values) and also make the arguments available to
callbacks by adding them to the handles structure.
For more information about using varargin, see the varargin reference page and
Support Variable Number of Inputs.
Passing Object Properties to an Opening Function
You can pass property name-value pairs as two successive command line arguments
when you run your program. If you pass a name-value pair that corresponds to a figure
property, MATLAB sets the property automatically. For example, my_gui('Color',
'Blue') sets the background color of the UI window to blue.
If you want your program to accept an input argument that is not a valid figure property,
then your code must recognize and handle that argument. Otherwise, the argument
is ignored. The following example is from the opening function for the Modal Question
Dialog template, available from the GUIDE Quick Start dialog box. The added code opens
the modal dialog with a message, specified from the command line or by another program
that calls this one. For example, this command displays the text, 'Do you want to
exit?' on the window.
myui('String','Do you want to exit?')
To accept this name-value pair, you must customize the opening function because
'String' is not a valid figure property. The Modal Question Dialog template file
contains code to performs these tasks:
Uses the nargin function to determine the number of user-specified arguments
(which do not include hObject, eventdata, and handles)
Parses varargin to obtain property name/value pairs, converting each name string to
lower case
Handles the case where the argument 'title' is used as an alias for the figure Name
property
Handles the case 'string' , assigning the following value as a String property to
the appropriate static text object
function modalgui_OpeningFcn(hObject, eventdata, handles, varargin)
.
.
.
% Insert custom Title and Text if specified by the user
% Hint: when choosing keywords, be sure they are not easily confused
7-9
Programming a GUIDE UI
The if block loops through the odd elements of varargin checking for property names
or aliases, and the case blocks assign the following (even) varargin element as a value
to the appropriate property of the figure or one of its components. You can add more
cases to handle additional property assignments that you want the opening function to
perform.
Initial Template Code
Initially, the input function template contains these lines of code:
handles.output = hObject adds a new element, output, to the handles
structure and assigns it the value of the input argument hObject, which is the figure
object.
guidata(hObject,handles) saves the handles structure. You must use the
guidata function to save any changes that you make to the handles structure. It is
not sufficient just to set the value of a handles field.
uiwait(handles.myui), initially commented out, blocks program execution until
uiresume is called or the window is closed. Note that uiwait allows the user access
to other MATLAB windows. Remove the comment symbol for this statement if you
want the UI to be blocking when it opens.
Output Function
The output function returns, to the command line, outputs that are generated during its
execution. It is executed when the opening function returns control and before control
returns to the command line. This means that you must generate the outputs in the
opening function, or call uiwait in the opening function to pause its execution while
other callbacks generate outputs.
7-10
Input Arguments
The output function has three input arguments: hObject, eventdata, and handles.
They are the same as described in GUIDE Callback Syntax on page 7-5.
Output Arguments
The output function has one output argument, varargout, which it returns to the
command line. By default, the output function assigns handles.output to varargout.
You can change the output by taking one of these actions:
Change the value of handles.output. It can be any valid MATLAB value including
a structure or cell array.
Add output arguments to varargout. The varargout argument is a cell array. It
can contain any number of output arguments. By default, GUIDE creates just one
output argument, handles.output. To create an additional output argument, create
a new field in the handles structure and add it to varargout using a command
similar to
varargout{2} = handles.second_output;
Related Examples
7-11
Programming a GUIDE UI
If you are creating a UI programmatically, (without GUIDE), then you can adapt the
example code into your code. To adapt an example into your code, omit the third input
argument, handles, from the function definition. Also, replace any references to the
handles array with the appropriate object handle. To associate the callback function
with the component, set the component's callback property to be a handle to the callback
function. For example, this command creates a push button component and sets the
Callback property to be a handle to the function, pushbutton1_callback.
pb =
uicontrol('Style','pushbutton','Callback',@pushbutton1_Callback);
Push Button
This code is an example of a push button callback function in GUIDE. Associate this
function with the push button Callback property to make it execute when the end user
clicks on the push button.
function pushbutton1_Callback(hObject, eventdata, handles)
% hObject
handle to pushbutton1 (see GCBO)
% eventdata reserved - to be defined in a future version of MATLAB
% handles
structure with handles and user data (see GUIDATA)
display('Goodbye');
close(gcf);
The first line of code, display('Goodbye'), displays the string, 'Goodbye', in the
Command Window. The next line gets a handle to the UI window using gcf and then
closes it.
Toggle Button
This code is an example of an example of a toggle button callback function in GUIDE.
Associate this function with the toggle button Callback property to make it execute
when the end user clicks on the toggle button.
function togglebutton1_Callback(hObject,eventdata,handles)
% hObject
handle to togglebutton1 (see GCBO)
% eventdata reserved - to be defined in a future version of MATLAB
% handles
structure with handles and user data (see GUIDATA)
% Hint: get(hObject,'Value') returns toggle state of togglebutton1
button_state = get(hObject,'Value');
7-13
Programming a GUIDE UI
if button_state == get(hObject,'Max')
display('down');
elseif button_state == get(hObject,'Min')
display('up');
end
The toggle buttons Value property matches the Min property when the toggle button
is up. The Value changes to the Max value when the toggle button is depressed. This
callback function gets the toggle buttons Value property and then compares it with the
Max and Min properties. If the button is depressed, then the function displays 'down' in
the Command Window. If the button is up, then the function displays 'up'.
Radio Button
This code is an example of a radio button callback function in GUIDE. Associate this
function with the radio button Callback property to make it execute when the end user
clicks on the radio button.
function radiobutton1_Callback(hObject, eventdata, handles)
% hObject
handle to radiobutton1 (see GCBO)
% eventdata reserved - to be defined in a future version of MATLAB
% handles
structure with handles and user data (see GUIDATA)
% Hint: get(hObject,'Value') returns toggle state of radiobutton1
if (get(hObject,'Value') == get(hObject,'Max'))
display('Selected');
else
display('Not selected');
end
The radio buttons Value property matches the Min property when the radio button is
not selected. The Value changes to the Max value when the radio button is selected. This
callback function gets the radio buttons Value property and then compares it with the
Max and Min properties. If the button is selected, then the function displays 'Selected'
in the Command Window. If the button is not selected, then the function displays 'Not
selected'.
Note Use a button group to manage exclusive selection behavior for radio buttons. See
Button Group on page 7-22 for more information.
7-14
Check Box
This code is an example of a check box callback function in GUIDE. Associate this
function with the check box Callback property to make it execute when the end user
clicks on the check box.
function checkbox1_Callback(hObject, eventdata, handles)
% hObject
handle to checkbox1 (see GCBO)
% eventdata reserved - to be defined in a future version of MATLAB
% handles
structure with handles and user data (see GUIDATA)
% Hint: get(hObject,'Value') returns toggle state of checkbox1
if (get(hObject,'Value') == get(hObject,'Max'))
display('Selected');
else
display('Not selected');
end
The check boxs Value property matches the Min property when the check box is not
selected. The Value changes to the Max value when the check box is selected. This
callback function gets the check boxs Value property and then compares it with the Max
and Min properties. If the check box is selected, the function displays 'Selected' in the
Command Window. If the check box is not selected, it displays 'Not selected'.
When the end user types characters inside the text field and presses the Enter key, the
callback function retrieves the string value and displays it in the Command Window.
7-15
Programming a GUIDE UI
To enable users to enter multiple lines of text, set the Max and Min properties to numeric
values that satisfy Max - Min > 1. For example, set Max to 2, and Min to 0 to satisfy
the inequality. In this case, the callback function triggers when the end user clicks on an
area in the UI that is outside of the text field.
Retrieve Numeric Values
If you want to interpret the contents of an edit text field as numeric values, then convert
the characters to numbers using the str2double function. The str2double function
returns NaN for nonnumeric input.
This code is an example of an edit text field callback function that interprets the users
input as numeric values.
function edit1_Callback(hObject, eventdata, handles)
% hObject
handle to edit1 (see GCBO)
% eventdata reserved - to be defined in a future version of MATLAB
% handles
structure with handles and user data (see GUIDATA)
% Hints: get(hObject,'String') returns contents of edit1 as text
% str2double(get(hObject,'String')) returns contents as a double
input = str2double(get(hObject,'string'));
if isnan(input)
errordlg('You must enter a numeric value','Invalid Input','modal')
uicontrol(hObject)
return
else
display(input);
end
When the end user enters values into the edit text field and presses the Enter key, the
callback function gets the value of the String property and converts it to a numeric
value. Then, it checks to see if the value is NaN (nonnumeric). If the input is NaN, then
the callback presents an error dialog box.
Slider
This code is an example of a slider callback function in GUIDE. Associate this function
with the slider Callback property to make it execute when the end user moves the
slider.
function slider1_Callback(hObject, eventdata, handles)
7-16
% hObject
% eventdata
% handles
When the end user moves the slider, the callback function gets the current value of the
slider and displays it in the Command Window. By default, the sliders range is [0, 1]. To
modify the range, set the sliders Max and Min properties to the maximum and minimum
values, respectively.
List Box
Populate Items in the List Box
If you are developing a UI using GUIDE, use the list box CreateFcn callback to add
items to the list box.
This code is an example of a list box CreateFcn callback that populates the list box with
the items, Red, Green, and Blue.
function listbox1_CreateFcn(hObject, eventdata, handles)
% hObject
handle to listbox1 (see GCBO)
% eventdata reserved - to be defined in a future version of MATLAB
% handles
empty - handles not created until after all CreateFcns
% Hint: listbox controls usually have a white background on Windows.
if ispc && isequal(get(hObject,'BackgroundColor'), ...
get(0,'defaultUicontrolBackgroundColor'))
set(hObject,'BackgroundColor','white');
end
set(hObject,'String',{'Red';'Green';'Blue'});
7-17
Programming a GUIDE UI
figure
uicontrol('Style','Listbox',...
'String',{'Red';'Green';'Blue'},...
'Position',[40 70 80 50]);
end
When the end user selects an item in the list box, the callback function performs the
following tasks:
Gets all the items in the list box and stores them in the variable, items.
7-18
Gets the numeric index of the selected item and stores it in the variable,
index_selected.
Gets the string value of the selected item and stores it in the variable,
item_selected.
Displays the selected item in the MATLAB Command Window.
The example, Interactive List Box in a GUIDE UI on page 8-33 shows how to
populate a list box with directory names.
Pop-Up Menu
Populate Items in the Pop-Up Menu
If you are developing a UI using GUIDE, use the pop-up menu CreateFcn callback to
add items to the pop-up menu.
This code is an example of a pop-up menu CreateFcn callback that populates the menu
with the items, Red, Green, and Blue.
function popupmenu1_CreateFcn(hObject, eventdata, handles)
% hObject
handle to popupmenu1 (see GCBO)
% eventdata reserved - to be defined in a future version of MATLAB
% handles
empty - handles not created until after all CreateFcns
% Hint: popupmenu controls usually have a white background on Windows.
if ispc && isequal(get(hObject,'BackgroundColor'),...
get(0,'defaultUicontrolBackgroundColor'))
set(hObject,'BackgroundColor','white');
end
set(hObject,'String',{'Red';'Green';'Blue'});
7-19
Programming a GUIDE UI
When the end user selects an item in the pop-up menu, the callback function performs
the following tasks:
Gets all the items in the pop-up menu and stores them in the variable, items.
Gets the numeric index of the selected item and stores it in the variable,
index_selected.
Gets the string value of the selected item and stores it in the variable,
item_selected.
Displays the selected item in the MATLAB Command Window.
7-20
Panel
Make the Panel Respond to Button Clicks
You can create a callback function that executes when the end user right-clicks or leftclicks on the panel. If you are working in GUIDE, then right-click the panel in the layout
and select View Callbacks > ButtonDownFcn to create the callback function.
This code is an example of a ButtonDownFcn callback in GUIDE.
function uipanel1_ButtonDownFcn(hObject, eventdata, handles)
% hObject
handle to uipanel1 (see GCBO)
% eventdata reserved - to be defined in a future version of MATLAB
% handles
structure with handles and user data (see GUIDATA)
display('Mouse button was pressed');
When the end user clicks on the panel, this function displays the text, 'Mouse button
was pressed', in the Command Window.
Resize the Window and Panel
By default, GUIDE UIs cannot be resized, but you can override this behavior by selecting
Tools > GUI Options and setting Resize behavior to Proportional.
Programmatic UIs can be resized by default, and you can change this behavior by setting
the Resize property of the figure on or off.
When your UI is resizable, the position of components in the window adjust as the user
resizes it. If you have a panel in your UI, then the panels size will change with the
windows size. Use the panels SizeChangedFcn callback to make your UI perform
specific tasks when the panel resizes.
This code is an example of a panels SizeChangedFcn callback in a GUIDE UI. When
the end user resizes the window, this function modifies the font size of static text inside
the panel.
function uipanel1_SizeChangedFcn(hObject, eventdata, handles)
% hObject
handle to uipanel1 (see GCBO)
% eventdata reserved - to be defined in a future version of MATLAB
% handles
structure with handles and user data (see GUIDATA)
set(hObject,'Units','Points')
panelSizePts = get(hObject,'Position');
panelHeight = panelSizePts(4);
7-21
Programming a GUIDE UI
set(hObject,'Units','normalized');
newFontSize = 10 * panelHeight / 115;
texth = findobj('Tag','text1');
set(texth,'FontSize',newFontSize);
If your UI has nested panels, then they will resize from the inside-out (in child-to-parent
order).
Note: To make the text inside a panel resize automatically, set the fontUnits property
to 'normalized'.
Button Group
Button groups are similar to panels, but they also manage exclusive selection of radio
buttons and toggle buttons. When a button group contains multiple radio buttons or
toggle buttons, the button group allows the end user to select only one of them.
Do not code callbacks for the individual buttons that are inside a button group. Instead,
use the button groups SelectionChangedFcn callback to respond when the end user
selects a button.
This code is an example of a button group SelectionChangedFcn callback that
manages two radio buttons and two toggle buttons.
function uibuttongroup1_SelectionChangedFcn(hObject, eventdata, handles)
% hObject
handle to the selected object in uibuttongroup1
% eventdata structure with the following fields
% EventName: string 'SelectionChanged' (read only)
% OldValue: handle of the previously selected object or empty
% NewValue: handle of the currently selected object
% handles
structure with handles and user data (see GUIDATA)
switch get(eventdata.NewValue,'Tag') % Get Tag of selected object.
case 'radiobutton1'
display('Radio button 1');
case 'radiobutton2'
display('Radio button 2');
case 'togglebutton1'
display('Toggle button 1');
case 'togglebutton2'
display('Toggle button 2');
end
7-22
When the end user selects a radio button or toggle button in the button group, this
function determines which button the user selected based on the buttons Tag property.
Then, it executes the code inside the appropriate case.
Note: The button groups SelectedObject property contains a handle to the button
that user selected. You can use this property elsewhere in your UI code to determine
which button the user selected.
Menu Item
The code in this section contains example callback functions that respond when the end
user selects Edit > Copy > To File in this menu.
7-23
Programming a GUIDE UI
7-24
% hObject
handle to copy_menu_item (see GCBO)
% eventdata reserved - to be defined in a future version of MATLAB
% handles
structure with handles and user data (see GUIDATA)
display('Copy menu item selected');
% -------------------------------------------------------------------function tofile_menu_item_Callback(hObject, eventdata, handles)
% hObject
handle to tofile_menu_item (see GCBO)
% eventdata reserved - to be defined in a future version of MATLAB
% handles
structure with handles and user data (see GUIDATA)
[filename,path] = uiputfile('myfile.m','Save file name');
The function names might be different in your UI, depending on the tag names you
specify in the GUIDE Menu Editor.
The callback functions trigger in response to these actions:
When the end user selects the Edit menu, the edit_menu_Callback function
displays the text, 'Edit menu selected', in the MATLAB Command Window.
When the end user hovers the mouse over the Copy menu item, the
copy_menu_item_Callback function displays the text, 'Copy menu item
selected', in the MATLAB Command Window.
When the end user clicks and releases the mouse button on the To File menu item,
the tofile_menu_item_Callback function displays a dialog box that prompts the
end user to select a destination folder and file name.
The tofile_menu_item_Callback function calls the uiputfile function to prompt
the end user to supply a destination file and folder. If you want to create a menu item
that prompts the user for an existing file, for example, if your UI has an Open File
menu item, then use the uigetfile function.
When you create a cascading menu like this one, the intermediate menu items trigger
when the mouse hovers over them. The final, terminating, menu item triggers when the
mouse button releases over the menu item.
How to Update a Menu Item Check
You can add a check mark next to a menu item to indicate that an option is enabled. In
GUIDE, you can select Check mark this item in the Menu Editor to make the menu
item checked by default. Each time the end user selects the menu item, the callback
function can turn the check on or off.
This code shows how to change the check mark next to a menu item.
7-25
Programming a GUIDE UI
if strcmp(get(hObject,'Checked'),'on')
set(hObject,'Checked','off');
else
set(hObject,'Checked','on');
end
The strcmp function compares two strings and returns true when they match. In this
case, it returns true when the menu items Checked property matches the string, 'on'.
See Create Menus for GUIDE UIs on page 6-77 for more information about creating
menu items in GUIDE. See Create Menus for Programmatic UIs on page 9-41 for
more information about creating menu items programmatically.
Table
This code is an example of the table callback function, CellSelectionCallback.
Associate this function with the table CellSelectionCallback property to make it
execute when the end user selects cells in the table.
function uitable1_CellSelectionCallback(hObject, eventdata, handles)
% hObject
handle to uitable1 (see GCBO)
% eventdata structure with the following fields
%
Indices: row and column indices of the cell(s) currently selected
% handles
structure with handles and user data (see GUIDATA)
data = get(hObject,'Data');
indices = eventdata.Indices;
r = indices(:,1);
c = indices(:,2);
linear_index = sub2ind(size(data),r,c);
selected_vals = data(linear_index);
selection_sum = sum(sum(selected_vals))
When the end user selects cells in the table, this function performs the following tasks:
Gets all the values in the table and stores them in the variable, data.
Gets the indices of the selected cells. These indices correspond to the rows and
columns in data.
Converts the row and column indices into linear indices. The linear indices allow you
to select multiple elements in an array using one command.
Gets the values that the end user selected and stores them in the variable,
selected_vals.
7-26
Sums all the selected values and displays the result in the Command Window.
This code is an example of the table callback function, CellEditCallback. Associate
this function with the table CellEditCallback property to make it execute when the
end user edits a cell in the table.
function uitable1_CellEditCallback(hObject, eventdata, handles)
% hObject
handle to uitable1 (see GCBO)
% eventdata structure with the following fields
% Indices: row and column indices of the cell(s) edited
% PreviousData: previous data for the cell(s) edited
% EditData: string(s) entered by the user
% NewData: EditData or its converted form set on the Data property.
% Empty if Data was not changed
% Error: error string when failed to convert EditData
data = get(hObject,'Data');
data_sum = sum(sum(data))
When the end user finishes editing a table cell, this function gets all the values in the
table and calculates the sum of all the table values. The ColumnEditable property must
be set to true in at least one column to allow the end user to edit cells in the table. For
more information about creating tables and modifying their properties in GUIDE, see
Add Components to the GUIDE Layout Area on page 6-13.
Axes
The code in this section is an example of an axes ButtonDownFcn that triggers when the
end user clicks on the axes.
7-27
Programming a GUIDE UI
The coordinates of the pointer display in the MATLAB Command Window when the end
user clicks on the axes (but not when that user clicks on another graphics object parented
to the axes).
7-28
Note: Most MATLAB plotting functions clear the axes and reset a number of axes
properties, including the ButtonDownFcn, before plotting data. To create an interface
that lets the end user plot data interactively, consider providing a component such as
a push button to control plotting. Such components properties are unaffected by the
plotting functions. If you must use the axes ButtonDownFcn to plot data, then use
functions such as line, patch, and surface.
More About
7-29
Programming a GUIDE UI
7-30
8
Examples of GUIDE UIs
Modal Dialog Box in GUIDE on page 8-2
UI That Accepts Parameters and Generates Plots on page 8-7
Synchronized Data Presentations in a GUIDE UI on page 8-17
Interactive List Box in a GUIDE UI on page 8-33
Plot Workspace Variables in a GUIDE UI on page 8-39
Automatically Refresh Plot in a GUIDE UI on page 8-44
On the Home tab, in the Environment section, click Preferences > GUIDE >
Show names in component palette.
In the GUIDE Quick Start dialog box, select Modal Question Dialog. Then, click
OK.
In the Property Inspector, select the String property. Then, change the existing
value to: Are you sure you want to close?
Then press Enter.
8-2
In the Save As dialog box, in the File name field, type modaldlg.fig.
In the GUIDE Quick Start dialog box, select Blank GUI (Default). Then, click OK.
From the component palette on the left, drag a push button into the layout area.
In the Property Inspector, select the String property. Then, change the existing
value to Close. Then press Enter.
8-3
In the Save dialog box, in the File name field, type closedlg.fig. Then, click
Save.
The code file, closedlg.m, opens in the Editor.
On the Editor tab, in the Navigate section, click Go To, and then select
pushbutton1_Callback.
Then, locate the following generated code in the Editor:
% --- Executes on button press in pushbutton1.
function pushbutton1_Callback(hObject, eventdata, handles)
% hObject
handle to close_pushbutton (see GCBO)
% eventdata reserved - to be defined in a future version of MATLAB
% handles
structure with handles and user data (see GUIDATA)
8-4
Add the following code immediately after the comment that begins with %
handles....
When the user clicks the Close button in the closedlg window, the
pushbutton1_Callback function executes this command:
user_response = modaldlg('Title','Confirm Close');
Recall that the modaldlg function is coded in the other program file, modaldlg.m.
That function displays a second window: the Confirm Close dialog box. The return
argument, user_response, is the users selection from that dialog box.
The switch command decides whether to close the first window (modaldlg) based on
the users selection.
9
MATLAB displays the closedlg window. Click the Close push button to execute
pushbutton1_Callback (in closedlg.m). That function calls modaldlg to display
the Confirm Close dialog box.
8-5
Click one of the buttons in the Confirm Close dialog box. When you click one of the
buttons, modaldlg.m closes the Confirm Close dialog box and returns your selection
to the calling function (pushbutton1_Callback). Then, the switch command in
that function decides whether to close the remaining open window.
Related Examples
More About
8-6
Dialog Boxes
8-7
Copy the example FIG-file and code file to your current (writeable) folder and open
the FIG-file in GUIDE:
copyfile(fullfile(docroot, 'techdoc','creating_guis',...
'examples','two_axes*.*')), fileattrib('two_axes*.*', '+w')
guide two_axes.fig
8-8
If you run the two_axes program and click the Plot button, the UI appears as shown
in the preceding figure. The code evaluates the expression displayed at the top of the UI
using parameters that you enter in the f1, f2, and t fields. The upper line graph displays
a Fourier transform of the computed signal displayed in the lower line graph.
UI Design
This UI plots two graphs depicting three input values:
Frequency one (f1)
Frequency two (f2)
A time vector (t)
When you click the Plot button, the program puts these values into a MATLAB
expression that is the sum of two sine functions:
x = sin(2*pi*f1*t) + sin(2*pi*f2*t)
Then, the program calculates the FFT (fast Fourier transform) of x and plots the data in
the frequency domain and the time domain in separate axes.
Default Values for Inputs
The program provides default values for the three inputs. This enables you to click the
Plot button and see a result as soon as you run the program. The defaults indicate
typical values.
The default values are created by setting the String property of the edit text. The
following figure shows how the value was set for the time vector.
8-9
8-10
a MATLAB expression. Because you can type many things that eval cannot handle,
the first task is to make sure that eval succeeded. The t_input_Callback uses try,
catch blocks to do the following:
Call eval with the t_input string inside the try block.
If eval succeeds, perform additional tests within the try block.
If eval generates an error, pass control to the catch block.
In that block, the callback disables the Plot button and changes its String to
'Cannot plot t'.
The remaining code in the try block makes sure that the variable t returned from eval
is a monotonically increasing vector of numbers with no more than 1000 elements. If t
passes all these tests, the callback enables Plot button and sets its String to 'Plot'. If
it fails any of the tests, the callback disables the Plot button and changes its String to
an appropriate short message. Here are the try and catch blocks from the callback:
function t_input_Callback(hObject, eventdata, handles)
% Disable the Plot button ... until proven innocent
set(handles.plot_button,'Enable','off')
try
t = eval(get(handles.t_input,'String'));
if ~isnumeric(t)
% t is not a number
set(handles.plot_button,'String','t is not numeric')
elseif length(t) < 2
% t is not a vector
set(handles.plot_button,'String','t must be vector')
elseif length(t) > 1000
% t is too long a vector to plot clearly
set(handles.plot_button,'String','t is too long')
elseif min(diff(t)) < 0
% t is not monotonically increasing
set(handles.plot_button,'String','t must increase')
else
% All OK; Enable the Plot button with its original name
set(handles.plot_button,'String','Plot')
set(handles.plot_button,'Enable','on')
return
end
% Found an input error other than a bad expression
% Give the edit text box focus so user can correct the error
uicontrol(hObject)
catch EM
% Cannot evaluate expression user typed
set(handles.plot_button,'String','Cannot plot t')
% Give the edit text box focus so user can correct the error
uicontrol(hObject)
end
8-12
The edit text callbacks execute when you enter text in an edit field and press Return
or click elsewhere in the UI. Even if you immediately click the Plot button, the edit text
callback executes before the plot button callback activates. When a callback receives
invalid input, it disables the Plot button, preventing its callback from running. Finally,
it restores focus to itself, selecting the text that did not validate so that you can re-enter
a value.
For example, here is the response to input of a time vector, [1 2 6 4 5 7 9], that does
not monotonically increase.
8-13
In this figure, the two plots reflect the last successful set of inputs, f1 = 31.41, f2
= 120, and t = [1 2 3 4 5 7 9]. The time vector [1 2 6 4 5 7 9] appears
highlighted so that you can enter a new, valid, value. The highlighting results from
executing the command uicontrol(hObject) in the preceding code listing.
Calculate Data
After constructing the string input parameters to numeric form and assigning
them to local variables, the next step is to calculate data for the two graphs. The
plot_button_Callback computes the time domain data using an expression of sines:
x = sin(2*pi*f1*t) + sin(2*pi*f2*t);
The callback computes the frequency domain data as the Fourier transform of the time
domain data:
y = fft(x,512);
Plot Data
The final task for the plot_button_Callback is to generate two plots. This involves:
Targeting plots to the appropriate axes. For example, this code directs a graph to the
time axes:
plot(handles.time_axes,t,x)
Calculate data
= sin(2*pi*f1*t) + sin(2*pi*f2*t);
= fft(x,512);
= y.*conj(y)/512;
= 1000*(0:256)/512;
8-15
Related Examples
More About
8-16
8-17
Copy the example FIG-file and code file to your current (writeable) folder and open
the FIG-file in GUIDE with the following commands:
copyfile(fullfile(docroot, 'techdoc','creating_guis',...
'examples','tablestat*.*')), fileattrib('tablestat*.*', '+w');
guide tablestat.fig;
8-18
Recreate the UI
In the GUIDE Layout Editor, the tablestat UI looks like this.
8-19
Perform the following steps in GUIDE and in the Property Inspector to generate the
layout:
1
In the Command Window, type guide, select the Blank GUI template, and then
click OK.
A long panel on the left. In the Property Inspector, set its Title property value
to Data Set.
A panel on the lower right, half the height of the first panel. In the Property
Inspector, set its Title property value to Data Statistics.
A panel above the Data Statistics panel. In the Property Inspector, set its
Title property to Sunspots v. Year Plots. This panel changes its name
when the type of plot changes.
8-20
Drag a second uitable inside the Data Statistics panel. Use the Table Property
Editor to set row values as follows:
a
In the Table Property Editor, select Rows from the list in the left-hand column.
to the right of
Select the bottom radio button, Show names entered below as row headers.
Type the nine strings listed in order on separate lines in the data entry pane,
and then click OK.
BackgroundColor: yellow (using the color picker).
ColumnName: Population and Selection.
Tag: data_stats.
TooltipString: statistics for table and selection.
RowNameto nine strings: N, Min, Max, Mean, Median, Std Dev, 1st Year,
Last Year, and Est. Period.
The Table Property Editor looks like this before you close it.
8-21
Drag out a second axes, leaving its name as axes2 inside the Sunspots v. Year
Plots panel, directly below the first axes.
Leave enough space below each axes to display the x-axis labels.
Identify the axes with labels. Using the Text tool, drag out a small rectangle in the
upper right corner of the upper axes (axes1). Double-click it, and in the Property
Inspector, change its String property to Population and its Tag property to
poplabel.
Place a second label in the lower axes (axes2), renaming this text object Selection
and setting its Tag property to sellabel.
Create a title for the UI. Using the Text tool, drag out a static text object at the top
left of the layout, above the data table. Double-click it, and in the Property Inspector,
change its String property to Zurich Sunspot Statistics, 1700-1987 and
its FontWeight property to bold.
10 Add a prompt above the axes; place a text label just above the Sunspots v. Year
Plots panel, near its right edge. Change its Tag property to newfig, its String
property to Right-click plots for larger view and its FontAngle property
to Italic.
11 Make a pop-up menu to specify the type of graph to plot. Using the Pop-up Menu tool
, drag out a pop-up menu just above the Sunspots v. Year panel, aligning it to
the panel's left edge. In the Property Inspector, set these properties:
String:
Sunspots v. Year Plots
FFT Periodogram Plots
Tag: plot_type
Tooltip: Choose type of data plot
Then, click the Callback property's icon. This creates a declaration called
plot_type_Callback, to which you add code later on.
8-22
13 Save the UI in GUIDE, naming it tablestat.fig. This action also saves the code
file as tablestat.m.
Initialize the Data Table
Although you can use the Opening Function to load data into a table, this example uses
GUIDE to put data into the Data Set table. This way, the data becomes part of the
figure after you save it. Initializing the table data causes the table to have the same
number of rows and columns as the variable that it contains:
1
Access the sunspot example data set. In the Command Window, type:
load sunspot.dat
The variable sunspot, a 288-by-2 double array, displays in the MATLAB workspace.
2
Open the Property Inspector for the data table by double-clicking the Data Set table.
In the Table Property Editor, select Table from the list in the left-hand column.
Select the bottom radio button, Change data value to the selected workspace
variable below.
From the list of workspace variables in the box below the radio button, select
sunspot and click OK.
8-23
% Number of rows
% First row
% Last row
% Peak period from FFT
Note: When assigning data to a uitable, use a cell array, as shown in the code for
setStats. You can assign data that you retrieve from a uitable to a numeric array,
however, only if it is entirely numeric. Storing uitable data in cell arrays enables tables
to hold numbers, strings of characters, or combinations of them.
The stats matrix is a 9-by-2 cell array in which each row is a separate statistic
computed from the table argument. The last statistic is not computed by setStats; it
comes from the plotPeriod function when it computes and plots the FFT periodogram
and is passed to setStats as the peak parameter.
8-24
8-25
The function updates the Data Statistics table and the plots. To perform the updates, it
calls the refreshDisplays function twice, which is a custom function added to the UI
code file. In between the two calls, the refreshDisplays function retrieves row indices
for the current selection from the currSelection member of the handles structure,
where they were cached by the data_table_CellSelectionCallback.
You can see the effect of toggling the plot type in the two illustrations that follow. The
one on the left shows the Sunspots v. Year plots, and the one on the right shows the FFT
Periodograms Plots. The selection in both cases is the years 19011950.
statistics observations from the second column for insertion into the Data Statistics
table on the right. The plotPeriod function (not generated by GUIDE) plots either the
raw data or a Fourier analysis of it.
The data_table_CellSelectionCallback function manages the application's
response to you selecting ranges of data. Ranges can be contiguous rows or separate
groups of rows; holding down the Ctrl key lets you add discontiguous rows to a selection.
Because the Cell Selection Callback is triggered as long as you hold the left mouse button
down within the table, the selection statistics and lower plot are refreshed until selection
is completed.
Selection data is generated during mouseDown events (mouse drags in the data table).
The uitable passes this stream of cell indices (but not cell values) via the eventdata
structure to the data_table_CellSelectionCallback callback. The callback's code
reads the indices from the Indices member of the eventdata.
When the callback runs (for each new value of eventdata), it turns the event data into a
set of rows:
selection = eventdata.Indices(:,1);
selection = unique(selection);
The event data contains a sequence of [row, column] indices for each table cell
currently selected, one cell per line. The preceding code trims the list of indices to a list
of selected rows, removing column indices. Then it calls the unique MATLAB function to
eliminate any duplicate row entries, which arise whenever you select both columns. For
example, suppose eventdata.Indices contains:
1
2
3
3
4
1
1
1
2
2
This indicates that you selected the first three rows in column one (Year) and rows three
and four in column two (Sunspots) by holding down the Ctrl key when selecting numbers
in the second column. The preceding code transforms the indices into this vector:
1
2
3
4
This vector enumerates all the selected rows. If the selection includes less than 11 rows
(as it does here) the callback returns, because computing statistics for a sample that
small is not useful.
8-27
When the selection contains 11 or more rows, the data table is obtained, the selection is
cached in the handles structure, and the refreshDisplays function is called to update
the selection statistics and plot, passing the portion of the table that you selected:
table = get(hObject,'Data');
handles.currSelection = selection;
guidata(hObject,handles)
refreshDisplays(table(selection,:), handles, 2)
Caching the list of rows in the selection is necessary because changing plot types can
force selection data to be replotted. As the plot_type_Callback has no access to the
data table's event data, it requires a copy of the most recent selection.
Update the Statistics Table and the Graphs
The code must update the Data Statistics table and the graphs above it when:
The UI is initialized, in its tablestat_OpeningFcn.
You select cells in the data table, in its data_table_CellSelectionCallback.
You select a different plot type, in the plot_type_Callback.
In each case, the refreshDisplays function is called to handle the updates. It in turn
calls two other custom functions:
setStats Computes summary statistics for the selection and returns them.
plotPeriod Plots the type of graph currently requested in the appropriate axes.
The refreshDisplays function identifies the current plot type and specifies the axes
to plot graphs into. After calling plotPeriod and setStats, it updates the Data
Statistics table with the recomputed statistics. Here is the code for refreshDisplays:
function refreshDisplays(table, handles, item)
if isequal(item,1)
ax = handles.axes1;
elseif isequal(item,2)
ax = handles.axes2;
end
peak = plotPeriod(ax, table,...
get(handles.plot_type,'Value'));
stats = get(handles.data_stats, 'Data');
stats = setStats(table, stats, item, peak);
set(handles.data_stats, 'Data', stats);
set(ax,'FontSize',7.0);
8-28
If you are reading this document in the MATLAB Help Browser, click the names of
the functions underlined above to see their complete code (including comments) in the
MATLAB Editor.
Display Graphs in New Figure Windows
The tablestat UI contains code to display either of its graphs in a larger size in a
new figure window when you right-click either axes and selects the pop-up menu item,
Open plot in new window. The static text string (tagged newfig) above the plot panel,
Right-click plots for larger view, informs you that this feature is available.
The axes respond by:
1
Saving the figure and axes handles in the handles structure for possible later use or
destruction.
Note: Handles are saved for both plots, but each time a new figure is created for
either of them, the new handles replace the old ones, if any, making previous figures
inaccessible from the UI.
To create the two context menus, from the GUIDE Tools menu, select the Menu Editor.
After you create the two context menus, attach one to the each axes, axes1 and axes2.
In the Menu Editor, for each menu:
1
2
Click the Context Menus tab to select the type of menu you are creating.
Click the New Context Menu icon
This creates a context menu in the Menu Editor workspace called untitled. It has
no menu items and is not attached to any UI object yet.
3
Select the new menu and in the Tag edit field in the Menu Properties panel, type
plot_axes1.
.
8-29
A menu item is displayed underneath the plot_axes1 item in the Menu Editor
workspace.
5
In the Menu Properties panel, type Open plot in new window for Label and
plot_ax1 for Tag. Do not set anything else for this item.
For more information about using the Menu Editor, see Create Menus for GUIDE UIs
on page 6-77.
Attach Context Menus to Axes
In the GUIDE Layout Editor, double-click axes1 (the top axes in the upper right
corner) to open it in the Property Inspector.
Perform the same steps for axes2, but select plot_axes2 as its UIContextMenu.
Code Context Menu Callbacks
The two context menu items perform the same actions, but create different objects. Each
has its own callback. Here is the plot_ax1_Callback callback for axes1:
function plot_ax1_Callback(hObject, eventdata, handles)
% hObject
handle to plot_ax1 (see GCBO)
% eventdata reserved - to be defined in a future version of MATLAB
% handles
structure with handles and user data (see GUIDATA)
%
% Displays contents of axes1 at larger size in a new figure
% Create a figure to receive this axes' data
axes1fig = figure;
% Copy the axes and size it to the figure
8-30
axes1copy = copyobj(handles.axes1,axes1fig);
set(axes1copy,'Units','Normalized',...
'Position',[.05,.20,.90,.60])
% Assemble a title for this new figure
str = [get(handles.uipanel3,'Title') ' for ' ...
get(handles.poplabel,'String')];
title(str,'Fontweight','bold')
% Save handles to new fig and axes in case
% we want to do anything else to them
handles.axes1fig = axes1fig;
handles.axes1copy = axes1copy;
guidata(hObject,handles);
Whenever you right-click one of the axes in the UI and select Open plot in new
window, a new figure is generated containing the graph in the axes. The callbacks do
not check whether a graph exists in the axes (axes2 is empty until you select cells in the
Data Set) or whether a previously opened figure contains the same graph. A new figure
is always created and the contents of axes1 or axes2 are copied into it. For example, you
could right-click a periodogram in axes1 and select Open plot in new window.
It is your responsibility to remove the new window when it is no longer needed. The
context menus can be programmed to do this. Because their callbacks call guidata to
save the handle of the last figure created for each of the axes, another callback can delete
or reuse either figure. For example, the plot_ax1_Callback and plot_ax2_Callback
callbacks could check guidata for a valid axes handle stored in handles.axes1copy or
handles.axes2copy, and reuse the axes instead of creating a new figure.
Related Examples
More About
8-32
Copy the example FIG-file and code file to your current (writeable) folder and open
the FIG-file in GUIDE and the with the following commands:
copyfile(fullfile(docroot, 'techdoc','creating_guis',...
'examples','lbox2*.*')), fileattrib('lbox2*.*', '+w')
guide lbox2.fig
8-33
The following code from lbox2.m shows the code for lbox2_OpeningFcn, which sets the
list box folder to:
The current folder, if no folder is specified.
The specified folder, if a folder is specified.
function lbox2_OpeningFcn(hObject, eventdata, handles, varargin)
% This function has no output args, see OutputFcn.
% hObject
handle to figure
% eventdata reserved - to be defined in a future version of MATLAB
% handles
structure with handles and user data (see GUIDATA)
% varargin
command line arguments to untitled (see VARARGIN)
% Choose default command line output for lbox2
handles.output = hObject;
8-34
Displays the current folder in the text box by setting its String property to the
output of the pwd command.
The load_listbox function is called by the opening function, as well as by the list box
callback.
function load_listbox(dir_path, handles)
cd (dir_path)
dir_struct = dir(dir_path);
[sorted_names,sorted_index] = sortrows({dir_struct.name}');
handles.file_names = sorted_names;
handles.is_dir = [dir_struct.isdir];
handles.sorted_index = sorted_index;
guidata(handles.figure1,handles)
set(handles.listbox1,'String',handles.file_names,...
'Value',1)
set(handles.text1,'String',pwd)
8-37
try
% Use open for other file types.
open(filename)
catch ex
errordlg(...
ex.getReport('basic'),'File Type Error','modal')
end
end
end
end
Related Examples
More About
8-38
8-39
Copy the example FIG-file and code file to your current (writeable) folder and open
the FIG-file in GUIDE with the following commands:
copyfile(fullfile(docroot, 'techdoc','creating_guis',...
'examples','lb.*')), fileattrib('lb.*', '+w')
guide lb.fig
function update_listbox(handles)
vars = evalin('base','who');
set(handles.listbox1,'String',vars)
The function input argument is the handles structure set up by the GUIDE. This
structure contains the handle of the list box, as well as the handles of all other
components in the UI.
The callback for the Update Listbox push button also calls update_listbox.
Returns two string variables, if there are two items selected. Otherwise
get_var_names displays an error dialog box stating that you must select two
variables.
Here is the code for get_var_names:
function [var1,var2] = get_var_names(handles)
list_entries = get(handles.listbox1,'String');
index_selected = get(handles.listbox1,'Value');
if length(index_selected) ~= 2
errordlg('You must select two variables',...
'Incorrect Selection','modal')
else
var1 = list_entries{index_selected(1)};
var2 = list_entries{index_selected(2)};
end
The command to evaluate is created by concatenating the strings and variables, and
looks like this:
try
evalin('base',['semilogx(',x,',',y,')'])
catch ex
errordlg(...
ex.getReport('basic'),'Error generating semilogx plot','modal')
end
The try/catch block handles errors resulting from attempting to graph inappropriate
data. When evaluated, the result of the command is:
plot(x,y)
8-42
The other two plotting buttons work in the same way, resulting in semilogx(x,y) and
semilogy(x,y).
Related Examples
More About
8-43
8-44
Copy the example FIG-file and code file to your current (writeable) folder and open
the FIG-file in GUIDE with the following commands:
copyfile(fullfile(docroot, 'techdoc','creating_guis','examples',...
'ex_guide_timergui*.*')), fileattrib('ex_guide_timergui*.*', '+w')
guide ex_guide_timergui.fig
8-45
For details about timer properties, methods, and events, see Use a MATLAB Timer
Object and the timer reference page.
ex_guide_timergui_OpeningFcn
ex_guide_timergui_OpeningFcn creates the timer using the following code:
handles.timer = timer(...
'ExecutionMode', 'fixedRate', ...
% Run timer repeatedly
'Period', 1, ...
% Initial period is 1 sec.
'TimerFcn', {@update_display,hObject}); % Specify callback
The opening function also initializes the slider Min, Max, and Value properties, and sets
the slider label to display the value:
set(handles.periodsldr,'Min',0.01,'Max',2)
set(handles.periodsldr,'Value',get(handles.timer('Period'))
set(handles.slidervalue,'String',...
num2str(get(handles.periodsldr,'Value')))
A call to surf renders the peaks data in the axes, adding the surfaceplot handle to the
handles structure:
handles.surf = surf(handles.display,peaks);
startbtn_Callback
startbtn_Callback calls timer start method if the timer is not already running:
if strcmp(get(handles.timer, 'Running'), 'off')
start(handles.timer);
end
stopbtn_Callback
stopbtn_Callback calls the timer stop method if the timer is currently running:
if strcmp(get(handles.timer, 'Running'), 'on')
stop(handles.timer);
end
periodsldr_Callback
periodsldr_Callback is called each time you move the slider. It sets the timer period
to the slider current value after removing unwanted precision:
% Read the slider value
8-47
period = get(handles.periodsldr,'Value');
% Timers need the precision of periods to be greater than about
% 1 millisecond, so truncate the value returned by the slider
period = period - mod(period,.01);
% Set slider readout to show its value
set(handles.slidervalue,'String',num2str(period))
% If timer is on, stop it, reset the period, and start it again.
if strcmp(get(handles.timer, 'Running'), 'on')
stop(handles.timer);
set(handles.timer,'Period',period)
start(handles.timer)
else
% If timer is stopped, reset its period only.
set(handles.timer,'Period',period)
end
The slider callback must stop the timer to reset its period, because timer objects do not
allow their periods to vary while they are running.
update_display
update_display is the callback for the timer object. It adds Gaussian noise to the
ZData of the surface plot:
handles = guidata(hfigure);
Z = get(handles.surf,'ZData');
Z = Z + 0.1*randn(size(Z));
set(handles.surf,'ZData',Z);
8-48
end
% Destroy timer
delete(handles.timer)
% Destroy figure
delete(hObject);
Related Examples
More About
8-49
9
Lay Out a Programmatic UI
Structure of Programmatic UI Code Files on page 9-2
Create Figures for Programmatic UIs on page 9-4
Add Components to a Programmatic UI on page 9-6
Lay Out a UI Programmatically on page 9-28
Customize Tabbing Behavior in a Programmatic UI on page 9-37
Create Menus for Programmatic UIs on page 9-41
Create Toolbars for Programmatic UIs on page 9-54
Fonts and Colors for Cross-Platform Compatibility on page 9-61
DPI-Aware Behavior in MATLAB on page 9-63
File Organization
Typically, a UI code file has the following ordered sections. You can help to maintain the
structure by adding comments that name the sections when you first create them.
1
Initialization tasks such as data creation and any processing that is needed to
construct the components. See Initialize a Programmatic UI on page 10-2 for
more information.
Construction of figure and components. For more information, see Create Figures
for Programmatic UIs on page 9-4 and Add Components to a Programmatic
UI on page 9-6.
Initialization tasks that require the components to exist, and output return. See
Initialize a Programmatic UI on page 10-2 for more information.
Callbacks for the components. Callbacks are the routines that execute in response to
user-generated events such as mouse clicks and key strokes. See Write Callbacks for
Apps Created Programmatically on page 10-5 for more information.
Utility functions.
File Template
This is a template you can use to create a UI code file:
function varargout = myui(varargin)
% MYUI Brief description of program.
%
Comments displayed at the command line in response
%
to the help command.
% (Leave a blank line following the help.)
9-2
Initialization tasks
Initialization tasks
end
Save the file in your current folder or at a location that is on your MATLAB path.
at the command line. Provide run-time arguments as appropriate. The file must reside on
your path or in your current folder.
When you execute the code, a fully functional copy of the UI displays on the screen. If the
file includes code to initialize the UI and callbacks to service the components, you can
manipulate components that it contains.
Related Examples
9-3
9-4
Property
Values
Description
MenuBar
Name
String
NumberTitle
Position
Resize
Toolbar
Property
Values
Description
none do not display the
figure toolbar.
auto display the figure
toolbar, but remove it if a user
interface control (uicontrol) is
added to the figure.
figure display the figure
toolbar.
Units
pixels, centimeters,
characters, inches,
normalized, points, Default is
pixels.
Visible
For a complete list of properties and for more information about the properties listed in
the table, see Figure Properties.
The following statement names the figure My UI, positions the figure on the screen, and
makes the UI invisible so that the user cannot see the components as they are added or
initialized. All other properties assume their defaults.
f = figure('Visible','off','Name','My UI',...
'Position',[360,500,450,285]);
Related Examples
9-5
9-6
The first uicontrol argument, f, specifies the parent container. In this case, the parent
is a figure, but you can also specify the parent to be any container, such as a panel or
button group.
The name-value pair arguments, 'Style','pushbutton', the uicontrol to be a push
button.
'String','Button 1' add the label, Button 1 to the push button.
'Position',[50 20 60 40] specifies the location and size of the push button. In this
example, the push button is 60 pixels wide and 40 high. It is positioned 50 pixels from
the left of the figure and 20 pixels from the bottom.
Displaying an Icon on a Push Button
To add an icon to a push button, assign the button's CData property to be an m-by-n-by-3
array of RGB values that define a truecolor image.
Radio Button
This code creates a radio button:
f = figure;
r = uicontrol(f,'Style','radiobutton',...
9-7
The first uicontrol argument, f, specifies the parent container. In this case, the parent
is a figure, but you can also specify the parent to be any container, such as a panel or
button group. If you have multiple radio buttons, you can manage their selection by
specifying the parent to be a button group. See Button Groups on page 9-21 for
more information.
The name-value pair arguments, 'Style','radiobutton' specifies the uicontrol to a
radio button.
'String','Indent nested functions.' specifies a label for the radio button.
'Value',1 selects the radio button by default. Set the Value property to be the value
of the Max property to select the radio button. Set the value to be the value of the Min
property to deselect the radio button. The default values of Max and Min are 1 and 0,
respectively.
'Position',[30 20 150 20] specifies the location and size of the radio button. In
this example, the radio button is 150 pixels wide and 20 high. It is positioned 30 pixels
from the left of the figure and 20 pixels from the bottom.
Toggle Button
This code creates a toggle button:
f = figure;
tb = uicontrol(f,'Style','togglebutton',...
'String','Left/Right Tile',...
'Value',0,'Position',[30 20 100 30]);
9-8
The first uicontrol argument, f, specifies the parent container. In this case, the parent
is a figure, but you can also specify the parent to be any container, such as a panel or
button group.
The name-value pair arguments, 'Style','togglebutton', specify the uicontrol to be
a toggle button.
'String','Left/Right Tile' puts a text label on the toggle button.
The 'Value',0 deselects the toggle button by default. To select (raise) the toggle button,
set Value equal to the Max property. To deselect the toggle button, set Value equal to
the Min property. By default, Min = 0 and Max = 1.
'Position',[30 20 100 30] specifies the location and size of the toggle button. In
this example, the toggle button is 100 pixels wide and 30 pixels high. It is positioned 30
pixels from the left of the figure and 20 pixels from the bottom.
Note: You can also display an icon on a toggle button. See Displaying an Icon on a Push
Button on page 9-7 for more information.
Check Box
This code creates a check box:
f = figure;
c = uicontrol(f,'Style','checkbox',...
'String','Display file extension',...
9-9
The first uicontrol argument, f, specifies the parent container. In this case, the parent
is a figure, but you can also specify the parent to be any container, such as a panel or
button group.
The name-value pair arguments, 'Style','checkbox', specify the uicontrol to be a
check box.
The next pair, 'String','Display file extension' puts a text label on the check
box.
The Value property specifies whether the box is checked. Set Value to the value of the
Max property (default is 1) to create the component with the box checked. Set Value to
Min (default is 0) to leave the box unchecked. Correspondingly, when the user clicks the
check box, MATLAB sets Value to Max when the user checks the box and to Min when
the user unchecks it.
The Position property specifies the location and size of the check box. In this example,
the check box is 130 pixels wide and 20 high. It is positioned 30 pixels from the left of the
figure and 20 pixels from the bottom.
Slider
This code creates a slider:
f = figure;
s = uicontrol(f,'Style','slider',...
'Min',0,'Max',100,'Value',25,...
'SliderStep',[0.05 0.2],...
'Position',[30 20 150 30]);
9-10
The first uicontrol argument, f, specifies the parent container. In this case, the parent
is a figure, but you can also specify the parent to be any container, such as a panel or
button group.
The name-value pair arguments, 'Style','slider' specifies the uicontrol to be a
slider.
'Min',0 and 'Max',100 specify the range of the slider to be [0, 100]. The Min property
must be less than Max.
'Value',25 sets the default slider position to 25. The number you specify for this
property must be within the range, [Min, Max].
'SliderStep',[0.05 0.2] specifies the fractional amount that the thumb moves
when the user clicks the arrow buttons or the slider trough (also called the channel). In
this case, the sliders thumb position changes by the smaller amount (5 percent) when the
user clicks an arrow button. It changes by the larger amount (20 percent) when the user
clicks the trough.
Specify SliderStep to be a two-element vector, [minor_step major_step]. The
value of minor_step must be less than or equal to major_step. To ensure the best
results, do not specify either value to be less than 1e-6. Setting major_step to 1 or
higher causes the thumb to move to Max or Min when the trough is clicked.
As major_step increases, the thumb grows longer. When major_step is 1, the thumb
is half as long as the trough. When major_step is greater than 1, the thumb continues
to grow, slowly approaching the full length of the trough. When a slider serves as a scroll
9-11
bar, you can uses this behavior to indicate how much of the document is currently visible
by changing the value of major_step.
'Position',[30 20 150 30] specifies the location and size of the slider. In this
example, the slider is 150 pixels wide and 30 high. It is positioned 30 pixels from the left
of the figure and 20 pixels from the bottom.
Note: On Mac platforms, the height of a horizontal slider is constrained. If the height you
set in the Position property exceeds this constraint, the displayed height of the slider is
the maximum allowed by the system. However, the value of the Position property does
not change to reflect this constraint.
Static Text
This code creates a static text component:
f = figure;
t = uicontrol(f,'Style','text',...
'String','Select a data set.',...
'Position',[30 50 130 30]);
9-12
The first uicontrol argument, f, specifies the parent container. In this case, the parent
is a figure, but you can also specify the parent to be any container, such as a panel or
button group.
The name-value pair arguments, 'Style','text' specify the uicontrol to be static text.
'String','Select a set' specifys the text that displays. If you specify a component
width that is too small to accommodate the specified String, MATLAB wraps the string.
'Position',[30 50 130 30] specifies the location and size of the static text. In this
example, the static text is 130 pixels wide and 20 high. It is positioned 30 pixels from the
left of the figure and 50 pixels from the bottom.
Editable Text Field
This code creates an editable text field, txtbox:
f = figure;
txtbox = uicontrol(f,'Style','edit',...
'String','Enter your name here.',...
'Position',[30 50 130 20]);
The first uicontrol argument, f, specifies the parent container. In this case, the parent
is a figure, but you can also specify the parent to be any container, such as a panel or
button group.
The name-value pair arguments, 'Style','edit', specify the style of the uicontrol to
be an editable text field.
9-13
If the value of Max - Min is less than or equal to 1, the editable text field allows only a
single line of input. If the width of the text field is too narrow for the string, MATLAB
displays only part of the string. The user can use the arrow keys to move the cursor over
the entire string.
9-14
Pop-Up Menu
This code creates a pop-up menu:
f = figure;
pm = uicontrol(f,'Style','popupmenu',...
'String',{'one','two','three','four'},...
'Value',1,'Position',[30 80 130 20]);
9-15
The first uicontrol argument, f, specifies the parent container. In this case, the parent
is a figure, but you can also specify the parent to be any container, such as a panel or
button group.
The name-value pair arguments, Style,'popupmenu', specify the uicontrol to be a popup menu.
'String',{'one','two','three','four'} defines the menu items.
'Value',1 sets the index of the item that is selected by default. Set Value to a scalar
that indicates the index of the selected item. A value of 1 selects the first item.
'Position',[30 80 130 20] specifies the location and size of the pop-up menu. In
this example, the pop-up menu is 130 pixels wide. It is positioned 30 pixels from the left
of the figure and 80 pixels from the bottom. The height of a pop-up menu is determined
by the font size; the height you set in the position vector is ignored.
List Box
This code creates a list box:
f = figure;
lb = uicontrol(f,'Style','listbox',...
'String',{'one','two','three','four'},...
'Position',[30 20 130 80],'Value',1);
9-16
The first uicontrol argument, f, specifies the parent container. In this case, the parent
is a figure, but you can also specify the parent to be any container, such as a panel or
button group.
The name-value pair arguments, 'Style','listbox', specify the uicontrol to be a list
box.
'String',{'one','two','three','four'} defines the list items.
'Position',[30 20 130 80] specifies the location and size of the list box. In this
example, the list box is 130 pixels wide and 80 high. It is positioned 30 pixels from the
left of the figure and 20 pixels from the bottom.
The final pair of arguments, Value,1 sets the list selection to the first item in the list.
To select a single item, set the Value property to be a scalar that indicates the position of
the item in the list.
To select more than one item, set the Value property to be a vector of values. To enable
your users to select multiple items, set the values of the Min and Max properties such
that Max - Min is greater than 1. Here is a list box that allows multiple selections and
has two items selected initially:
lb = uicontrol(f,'Style','listbox',...
'String',{'one','two','three','four'},...
'Max',2,'Min',0,'Value',[1 3],...
'Position',[30 20 130 80]);
9-17
Tables
This code creates a table and populates it with the values returned by magic(5).
f = figure;
tb = uitable(f,'Data',magic(5));
The first uitable argument, f, specifies the parent container. In this case, the parent
is a figure, but you can also specify the parent to be any container, such as a panel or
button group.
The name-value pair arguments, 'Data',magic(5), specifies the table data. In this
case, the data is the 5-by-5 matrix returned by the magic(5) command.
You can adjust the width and height of the table to accommodate the extent of the data.
The uitables Position property controls the outer bounds of the table, and the Extent
property indicates the extent of the data. Set the last two values in the Position
property to the corresponding values in the Extent property:
tb.Position(3) = tb.Extent(3);
tb.Position(4) = tb.Extent(4);
9-18
You can change several other characteristics of the table by setting certain properties:
To control the users ability to edit the table cells, set the ColumnEditable property.
To make your application respond when the user edits a cell, define a
CellEditCallback function.
To add or change row striping, set the RowStriping property.
To specify row and column names, set the RowName and ColumnName properties.
To format the data in the table, set the ColumnFormat property.
See Uitable Properties for the entire list of properties.
If you are building a UI using GUIDE, you can set many of the uitable properties using
the Table Property Editor. For more information, see Create a Table on page 6-50.
Panels
This code creates a panel:
f = figure;
p = uipanel(f,'Title','My Panel',...
'Position',[.25 .1 .5 .8]);
9-19
The first argument passed to uipanel, f, specifies the parent container. In this case,
the parent is a figure, but you can also specify the parent to be any container, such as
another panel or a button group.
'Title','My Panel' specifies a title to display on the panel.
'Position',[.25 .1 .5 .8] specifies the location and size of the panel as a fraction
of the parent container. In this case, the panel is 50 percent of the width of the figure and
80 percent of its height. The left edge of the panel is located at 25 percent of the figures
width from the left. The bottom of the panel is located 10 percent of the figures height
from the bottom. If the figure is resized, the panel retains its original proportions.
The following commands add two push buttons to the panel. Setting the Units property
to 'normalized' causes the Position values to be interpreted as fractions of the
parent panel. Normalized units allow the buttons to retain their original proportions
when the panel is resized.
9-20
b1 = uicontrol(p,'Style','pushbutton','String','Button 1',...
'Units','normalized',...
'Position',[.1 .55 .8 .3]);
b2 = uicontrol(p,'Style','pushbutton','String','Button 2',...
'Units','normalized',...
'Position',[.1 .15 .8 .3]);
Button Groups
This code creates a button group:
f = figure;
bg = uibuttongroup(f,'Title','My Button Group',...
'Position',[.1 .2 .8 .6]);
9-21
The first argument passed to uibuttongroup, f, specifies the parent container. In this
case, the parent is a figure, but you can also specify the parent to be any container, such
as a panel or another button group.
'Title','My Button Group' specifies a title to display on the button group.
'Position',[.1 .2 .8 .6] specifies the location and size of the button group as a
fraction of the parent container. In this case, the button group is 80 percent of the width
of the figure and 60 percent of its height. The left edge of the button group is located at
10 percent of the figures width from the left. The bottom of the button group is located 20
percent of the figures height from the bottom. If the figure is resized, the button group
retains its original proportions.
The following commands add two radio buttons to the button group. Setting the Units
property to 'normalized' causes the Position values to be interpreted as fractions
of the parent panel. Normalized units allow the buttons to retain their original relative
positions when the button group is resized.
9-22
rb1 = uicontrol(bg,'Style','radiobutton','String','Red',...
'Units','normalized',...
'Position',[.1 .6 .3 .2]);
rb2 = uicontrol(bg,'Style','radiobutton','String','Blue',...
'Units','normalized',...
'Position',[.1 .2 .3 .2]);
By default, the first radio button added to the uibuttongroup is selected. To override this
default, set any other radio buttons Value property to its Max property value.
Button groups manage the selection of radio buttons and toggle buttons by allowing only
one button to be selected within the group. You can determine the currently selected
button by querying the uibuttongroups SelectedObject property.
Axes
This code creates an axes in a figure:
9-23
f = figure;
ax = axes('Parent',f,'Position',[.15 .15 .7 .7]);
The first two arguments passed to the axes function, 'Parent',f specify the parent
container. In this case, the parent is a figure, but you can also specify the parent to be
any container, such as a panel or button group.
'Position',[.15 .15 .7 .7] specifies the location and size of the axes as a fraction
of the parent figure. In this case, the axes is 70 percent of the width of the figure and
70 percent of its height. The left edge of the axes is located at 15 percent of the figures
width from the left. The bottom of the axes is located 15 percent of the figures height
from the bottom. If the figure is resized, the axes retains its original proportions.
Prevent Customized Axes Properties from Being Reset
Data graphing functions, such as plot, image, and scatter, reset axes properties
before they draw into an axes. This can be a problem when you want to maintain
consistency of axes limits, ticks, colors, and font characteristics in a UI.
9-24
The default value of the NextPlot axes property, 'replace' allows the graphing
functions to reset many property values. In addition, the 'replace' property value
allows MATLAB to remove all callbacks from the axes whenever a graph is plotted.
If you create an axes in a UI window, consider setting the NextPlot property to
'replacechildren'. You might need to set this property prior to changing the contents
of an axes:
ax.NextPlot = 'replacechildren';
ActiveX Controls
ActiveX components enable you to display ActiveX controls in your UI. They are available
only on the Microsoft Windows platform.
An ActiveX control can be the child only of a figure. It cannot be the child of a panel or
button group.
See Creating an ActiveX Control about adding an ActiveX control to a figure. See
Create COM Objects for general information about ActiveX controls.
9-25
'Century Schoolbook'
'normal'
'normal'
9
'points'
You can use this information to set font characteristics of a component in the UI:
btn = uicontrol;
btn.FontName = myfont.FontName;
btn.FontSize = myfont.FontSize;
9-26
Related Examples
9-27
9-28
You can query or change the outer bounds of the figure by using the OuterPosition
property. Like the Position property, the OuterPosition is a four element row vector:
f.OuterPosition
ans =
250
124
576
512
The left outer edge of this figure is 250 pixels from the left side of the screen. Its bottom
outer edge is 124 pixels up from the bottom of the screen. The area enclosed by the outer
bounds of the figure is 576 pixels wide by 512 pixels high.
9-29
132
560
420
9-30
258
258
474
248
Your choice of units can affect the appearance and resizing behavior of the UI:
If you want the UI components to scale proportionally with the figure when the user
resizes the figure, set the Units property of the components to 'normalized'.
UI Components do not scale proportionally inside the figure when their Units
property is set to 'inches', 'centimeters', 'points', 'pixels', or
'characters'.
If you are developing a cross-platform UI, then set the Units property to 'points'
or 'characters' to make the layout consistent across all platforms.
Example of a Simple Layout
Here is the code for a simple UI containing an axes and a button. To see how it works,
copy and paste this code into the editor and run it.
function myui
% Add the UI components
hs = addcomponents;
% Make figure visible after adding components
hs.fig.Visible = 'on';
function hs = addcomponents
% add components, save handles in a struct
hs.fig = figure('Visible','off',...
9-31
'Resize','off',...
'Tag','fig');
hs.btn = uicontrol(hs.fig,'Position',[10 340 70 30],...
'String','Plot Sine',...
'Tag','button',...
'Callback',@plotsine);
hs.ax = axes('Parent',hs.fig,...
'Position',[0.20 0.13 0.71 0.75],...
'Tag','ax');
end
function plotsine(hObject,callbackdata)
theta = 0:pi/64:6*pi;
y = sin(theta);
plot(hs.ax,theta,y);
end
end
The main function, myui, calls the addcomponents function. The addcomponents
function returns a structure, hs, containing the handles to all the UI components.
The addcomponents function creates a figure, an axes, and a button, each with
specific Position values.
Notice that the Resize property of the figure is 'off'. This value disables the
resizing capability of the figure.
Notice that the Visible property of the figure is 'off' inside the
addcomponents function. The value changes to 'on' after addcomponents
returns to the calling function. Doing this delays the figure display until after
MATLAB adds all the components. Thus, the resulting UI has a clean appearance
when it starts up.
The plotsine function plots the sine function inside the axes when the user clicks
the button.
9-32
9-33
If your UI has another container, such as a uipanel or uibuttongroup, you can manage
the layout of the containers child components in a separate callback function that you
assign to the SizeChangedFcn property.
The SizeChangedFcn callback executes only under these circumstances:
The container becomes visible for the first time.
The container is visible while its drawable area changes.
The container becomes visible for the first time after its drawable area changes. This
situation occurs when the drawable area changes while the container is invisible and
becomes visible later.
Note: Typically, the drawable area changes at the same time the outer bounds change.
However, adding or removing menu bars or tool bars to a figure causes the outer bounds
to change while the drawable area remains constant. Therefore, the SizeChangedFcn
callback does not execute when you add or remove menu bars or tool bars.
This UI is a resizable version of the simple UI defined in Example of a Simple
Layout on page 9-31. This code includes a figure SizeChangedFcn callback called
resizeui. The resizeui function calculates new Position values for the button and
axes when the user resizes the window. The button appears to be stationary when the
user resizes the window. The axes scales with the figure.
function myui
% Add the UI components
hs = addcomponents;
% Make figure visible after adding components
hs.fig.Visible = 'on';
function hs = addcomponents
% Add components, save handles in a struct
hs.fig = figure('Visible','off',...
'Tag','fig',...
'SizeChangedFcn',@resizeui);
hs.btn = uicontrol(hs.fig,'String',...
'Plot Sine',...
'Callback',@plotsine,...
'Tag','button');
hs.ax = axes('Parent',hs.fig,...
9-34
'Units','pixels',...
'Tag','ax');
end
function plotsine(hObject,callbackdata)
theta = 0:pi/64:6*pi;
y = sin(theta);
plot(hs.ax,theta,y);
end
function resizeui(hObject,callbackdata)
% Get figure width and height
figwidth = hs.fig.Position(3);
figheight = hs.fig.Position(4);
% Set button position
bheight = 30;
bwidth = 70;
bbottomedge = figheight - bheight - 50;
bleftedge = 10;
hs.btn.Position = [bleftedge bbottomedge bwidth bheight];
% Set axes position
axheight = .75*figheight;
axbottomedge = max(0,figheight - axheight - 30);
axleftedge = bleftedge + bwidth + 30;
axwidth = max(0,figwidth - axleftedge - 50);
hs.ax.Position = [axleftedge axbottomedge axwidth axheight];
end
end
The resizeui function sets the location and size of the button and axes whenever the
user resizes the window:
The button height, width, and left edge stay the same when the window resizes.
The bottom edge of the button, bbottomedge, allows 50 pixels of space between the
top of the figure and the top of the button.
The value of the axes height, axheight, is 75% of the available height in the figure.
The value of the axes bottom edge, axbottomedge, allows 30 pixels of space between
the top of the figure and the top of the axes. In this calculation, the max function
limits this value to nonnegative values.
9-35
The value of the axes width, axwidth, allows 50 pixels of space between the right side
of the axes and the right edge of the figure. In this calculation, the max function limits
this value to nonnegative values.
Notice that all the layout code is inside the resizeui function. It is a good practice to
put all the layout code inside the SizeChangedFcn callback to ensure the most accurate
results.
Also, it is important to delay the display of the entire UI window until after all the
variables that a SizeChangedFcn callback uses are defined. Doing so can prevent the
SizeChangedFcn callback from returning an error. To delay the display of the window,
set the Visible property of the figure to 'off'. After you define all the variables that
your SizeChangedFcn callback uses, set the Visible property to 'on'.
More About
9-36
9-37
You can obtain the default tab order for a figure, panel, or button group by looking at its
Children property. For the example, this command gets the children of the uipanel, ph.
ch = ph.Children
ch =
9-38
(Surf)
(Mesh)
(Contour)
The default tab order is the reverse of the child order: Contour, then Mesh, then Surf.
Note Displaying the children in this way shows only those children that have their
HandleVisibility property set to 'on'. Use allchild to retrieve children regardless
of their handle visibility.
In this example, the default order is pop-up menu followed by the panel's Contour,
Mesh, and Surf push buttons (in that order), and then back to the pop-up menu. You
cannot tab to the axes component or the static text component.
Try modifying the code to create the pop-up menu following the creation of the Contour
push button and before the Mesh push button. Now execute the code to create the UI
and tab through the components. This code change does not alter the default tab order.
This is because the pop-up menu does not have the same parent as the push buttons. The
figure is the parent of the panel and the pop-up menu.
(Surf)
(Mesh)
(Contour)
Next, call the uistack function to change the tab order of buttons. This code moves the
Mesh button up one level, making it the last item in the tab order.
uistack(ch(2),'up',1);
9-39
The tab order of the three buttons is now Contour, then Surf, then Mesh.
This command shows the new child order.
ph.Children
ans =
3x1 UIControl array:
UIControl
UIControl
UIControl
(Mesh)
(Surf)
(Contour)
Note Tab order also affects the stacking order of components. If components overlap,
those that appear higher in the child order, display on top of those that appear lower in
the order.
9-40
Where mh is the handle of the resulting menu or menu item. See the uimenu reference
page for other valid syntaxes.
These topics discuss use of the MATLAB standard menu bar menus and describe
commonly used menu properties and offer some simple examples.
Display Standard Menu Bar Menus on page 9-41
Commonly Used Properties on page 9-42
How Menus Affect Figure Docking on page 9-43
Menu Bar Menu on page 9-45
Display Standard Menu Bar Menus
Displaying the standard menu bar menus is optional. This figures menu bar contains the
standard menus.
9-41
If you use the standard menu bar menus, any menus you create are added to it. If you
choose not to display the standard menu bar menus, the menu bar contains only the
menus that you create. If you display no standard menus and you create no menus, the
menu bar itself does not display.
Use the figure MenuBar property to display or hide the MATLAB standard menu bar
shown in the preceding figure. Set MenuBar to figure (the default) to display the
standard menus. Set MenuBar to none to hide them.
fh.MenuBar = 'figure';
fh.MenuBar = 'none';
Property
Values
Description
Accelerator
Alphabetic character
Checked
Enable
HandleVisibility
Label
String
Menu label.
To display the & character in a label,
use two & characters in the string.
The words remove, default, and
factory (case sensitive) are reserved.
To use one of these as a label, prepend
a backslash (\) to the string. For
example, \remove yields remove.
Position
Scalar. Default is 1.
Separator
For a complete list of properties and for more information about the properties listed in
the table, see Uimenu Properties.
How Menus Affect Figure Docking
When you customize the menu bar or toolbar, you can control the display of the window's
docking controls by setting the DockControls property. You might not need menus for
your UI, but if you want the user to be able to dock or undock the UI, it must contain a
menu bar or a toolbar. This is because docking is controlled by the docking icon, a small
curved arrow near the upper-right corner of the menu bar or the toolbar, as the following
illustration shows.
9-43
Figure windows with a standard menu bar also have a Desktop menu from which the
user can dock and undock them.
To display the docking arrow and the Desktop > Dock Figure menu item, the figure
property DockControls must be set to 'on'. You can set this property in the Property
Inspector. In addition, the MenuBar and/or ToolBar figure properties must be set to
'on' to display docking controls.
The WindowStyle figure property also affects docking behavior. The default is
'normal', but if you change it to 'docked', then the following applies:
The UI opens docked in the desktop when you run it.
The DockControls property is set to 'on' and cannot be turned off until
WindowStyle is no longer set to 'docked'.
If you undock a UI created with WindowStyle set to 'docked', the window will have
not have a docking arrow unless the figure displays a menu bar or a toolbar. When
the window has no docking arrow, users can undock it from the desktop, but will be
unable to redock it.
To summarize, you can display docking controls with the DockControls property as
long as it is not in conflict with the figure's WindowStyle property.
Note: Modal dialogs (figures with the WindowStyle property set to 'modal') cannot
have menu bars, toolbars, or docking controls.
For more information, see the DockControls, MenuBar, ToolBar, and WindowStyle
property descriptions on the Figure Properties page.
9-44
If your UI does not display the standard menu bar, MATLAB creates a menu bar if none
exists and then adds the menu to it.
9-45
This command adds a separator line preceding the second menu item.
eh2.Separator = 'on';
9-46
The following statements add two menu subitems to Item 1, assign each subitem a
keyboard accelerator, and disable the first subitem.
seh1 = uimenu(eh1,'Label','Choice 1','Accelerator','C',...
'Enable','off');
seh2 = uimenu(eh1,'Label','Choice 2','Accelerator','H');
The Accelerator property adds keyboard accelerators to the menu items. Some
accelerators may be used for other purposes on your system and other actions may result.
The Enable property disables the first subitem Choice 1 so a user cannot select it when
the menu is first created. The item appears dimmed.
Note After you have created all menu items, set their HandleVisibility properties
off by executing the following statements:
menuhandles = findall(figurehandle,'type','uimenu');
menuhandles.HandleVisibility = 'off';
See the section, Menu Item on page 7-23, for information about programming menu
items.
9-47
Add menu items to the context menu using the uimenu function.
Associate the context menu with a graphics object using the object's UIContextMenu
property.
Subsequent topics describe commonly used context menu properties and explain each of
these steps:
Commonly Used Properties on page 9-48
Create the Context Menu Object on page 9-49
Add Menu Items to the Context Menu on page 9-49
Associate the Context Menu with Graphics Objects on page 9-50
Force Display of the Context Menu on page 9-52
Commonly Used Properties
The most commonly used properties needed to describe a context menu object are shown
in the following table. These properties apply only to the menu object and not to the
individual menu items.
Property
Values
HandleVisibility
Parent
Figure handle
Position
2-element vector:
[distance from left,
distance from bottom].
Default is [0 0].
9-48
Description
Property
Values
Description
Visible
For a complete list of properties and for more information about the properties listed in
the table, see Uicontextmenu Properties.
Create the Context Menu Object
Use the uicontextmenu function to create a context menu object. The syntax is
handle = uicontextmenu('PropertyName',PropertyValue,...)
The parent of a context menu must always be a figure. Use the Parent property to
specify the parent of a uicontextmenu. If you do not specify the Parent property, the
parent is the current figure as specified by the root CurrentFigure property.
The following code creates a figure and a context menu whose parent is the figure. At this
point, the figure is visible, but not the menu.
fh = figure('Position',[300 300 400 225]);
cmenu = uicontextmenu('Parent',fh,'Position',[10 215]);
Note Force Display of the Context Menu on page 9-52 explains the use of the
Position property.
Add Menu Items to the Context Menu
Use the uimenu function to add items to the context menu. The items appear on the
menu in the order in which you add them. The following code adds three items to the
context menu created above.
9-49
You can specify any applicable Uimenu Properties when you define the context menu
items. See the uimenu reference page and Add Menu Bar Menus on page 9-41 for
information about using uimenu to create menu items. Note that context menus do not
have an Accelerator property.
Note After you have created the context menu and all its items, set their
HandleVisibility properties to 'off' by executing the following statements:
cmenuhandles = findall(figurehandle,'type','uicontextmenu');
cmenuhandles.HandleVisibility = 'off';
menuitemhandles = findall(cmenuhandles,'type','uimenu');
menuitemhandles.HandleVisibility = 'off';
9-50
This code associates the context menu with the figure and with the axes by setting the
UIContextMenu property of the figure and the axes to the handle cmenu of the context
menu.
fh.UIContextMenu = cmenu;
ah.UIContextMenu = cmenu;
% Figure
% Axes
Right-click on the figure or on the axes. The context menu appears with its upper-left
corner at the location you clicked. Right-click on the panel or its push button. The context
menu does not appear.
9-51
The context menu displays 10 pixels from the left of the figure and 215 pixels from the
bottom.
9-52
If you set the context menu Visible property to off, or if the user clicks outside the
context menu, the context menu disappears.
More About
9-53
The output arguments, tbh, pth, and tth are the handles, respectively, of the resulting
toolbar, push tool, and toggle tool. See the uitoolbar, uipushtool, and uitoggletool
reference pages for other valid syntaxes.
Subsequent topics describe commonly used properties of toolbars and toolbar tools, offer
a simple example, and discuss use of the MATLAB standard toolbar:
9-54
Property
Values
Description
CData
Property
Values
Description
displayed on either a push button or
toggle button.
HandleVisibility
Separator
State
TooltipString
String
For a complete list of properties and for more information about the properties listed
in the table, see the Uitoolbar Properties, Uipushtool Properties, and Uitoggletool
Properties.
Toolbars
The following statements add a toolbar to a figure, and then add a push tool and a toggle
tool to the toolbar. By default, the tools are added to the toolbar, from left to right, in the
order they are created.
% Create the toolbar
fh = figure;
tbh = uitoolbar(fh);
% Add a push tool to the toolbar
a = [.20:.05:0.95];
img1(:,:,1) = repmat(a,16,1)';
img1(:,:,2) = repmat(a,16,1);
img1(:,:,3) = repmat(flip(a),16,1);
pth = uipushtool(tbh,'CData',img1,...
'TooltipString','My push tool',...
'HandleVisibility','off');
9-55
TooltipString specifies the tooltips for the push tool and the toggle tool as My push
tool and Your toggle tool, respectively.
In this example, setting the toggle tool Separator property to on creates a dividing line
to the left of the toggle tool.
You can change the order of the tools by modifying the child vector of the parent toolbar.
For this example, execute the following code to reverse the order of the tools.
oldOrder = allchild(tbh);
newOrder = flipud(oldOrder);
tbh.Children = newOrder;
This code uses flipud because the Children property is a column vector.
Use the delete function to remove a tool from the toolbar. The following statement
removes the
toggle tool from the toolbar. The toggle tool handle is tth.
delete(tth)
9-57
If necessary, you can use the findall function to determine the handles of the tools on a
particular toolbar.
Note After you have created a toolbar and its tools, set their HandleVisibility
properties off by executing statements similar to the following:
toolbarhandle.HandleVisibility = 'off';
toolhandles = toolbarhandle.Children;
toolhandles.HandleVisibility = 'off';
9-58
To remove a tool from the standard toolbar, determine the handle of the tool to be
removed, and then use the delete function to remove it. The following code deletes the
toggle tool that was added to the standard toolbar above.
delete(tth)
If necessary, you can use the findall function to determine the handles of the tools on
the standard toolbar.
9-59
See Also
More About
9-60
9-62
Visual Appearance
Here are the visual effects you might notice on high-DPI systems:
The MATLAB desktop, graphics, fonts, and most UI components look sharp and
render with full graphical detail on Macintosh and Windows systems.
9-63
When you create a graphics or UI object, and specify the Units as 'pixels', the size
of that object is now consistent with the size of other objects. For example, the size of
a push button (specified in pixels) is now consistent with the size of the text on that
push button (specified in points).
Elements in the MATLAB Toolstrip look sharper than in previous releases. However,
icons in the Toolstrip might still look slightly blurry on some systems.
On Windows systems, the MATLAB Toolstrip might appear larger than in previous
releases.
9-64
On Windows systems, the size of the Command Window fonts and Editor fonts might
be larger than in previous releases. In particular, you might see a difference if you
have nondefault font sizes selected in MATLAB preferences. You might need to adjust
those font sizes to make them look smaller.
You might see differences on multiple-display systems that include a combination
of different displays (for example, some, but not all of the displays are high-DPI).
Graphical elements might look different across displays on those systems.
9-65
The factory value cannot be queried either. This command returns an error as well:
get(groot,'FactoryRootScreenPixelsPerInch')
See Also
9-66
10
Code a Programmatic UI
Initialize a Programmatic UI on page 10-2
Write Callbacks for Apps Created Programmatically on page 10-5
10
Code a Programmatic UI
Initialize a Programmatic UI
Programs that present a UI might perform these tasks when you launch them:
Define default values
Set UI component property values
Process input arguments
Hide the figure window until all the components are created
When you develop a UI, consider grouping these tasks together in your code file. If an
initialization task involves several steps, consider creating a separate function for that
task.
Examples
Declare Variables for Input and Output Arguments
These are typical declarations for input and output arguments.
mInputArgs = varargin; % Command line arguments
mOutputArgs = {};
Each row of the cell array defines one property. It specifies, in order, the name of the
property, the routine that is called to validate the input, and the name of the variable
that holds the property value.
10-2
Initialize a Programmatic UI
After you have added all the components to the figure window, make the figure visible:
hMainFigure.Visible = 'on';
Most components have a Visible property. Thus, you can also use this property to make
individual components invisible.
Return Output to the User
If your program allows an output argument, and the user specifies such an argument,
then you want to return the expected output. The code that provides this output usually
appears just before the programs main function returns.
In the example shown here,
10-3
10
Code a Programmatic UI
A call to uiwait blocks execution until uiresume is called or the current figure is
deleted.
When the user clicks OK, that push buttons callback calls the uiresume function.
mIconData contains the icon that the user created or edited. mOutputArgs is a cell
array defined to hold the output arguments. nargout indicates how many output
arguments the user has supplied. varargout contains the optional output arguments
returned by the program. See the complete Icon Editor code file for more information.
Related Examples
10-4
Callback
uicontextmenu, uicontrol,
uimenu
CellEditCallback
End user edits a value in a table
whose cells are editable.
uitable
CellSelectionCallback
End user selects cells in a table.
uitable
ClickedCallback
End user clicks the push tool or
toggle tool with the left mouse
button.
uitoggletool, uipushtool
CloseRequestFcn
The figure closes.
figure
10-5
10
Code a Programmatic UI
CreateFcn
DeleteFcn
KeyPressFcn
OffCallback
uitoggletool
OnCallback
uitoggletool
figure, uipanel,
uibuttongroup
SelectionChangedFcn
End user selects a different radio
button or toggle button within a
button group.
uibuttongroup
WindowButtonDownFcn
End user presses a mouse button
while the pointer is in the figure
window.
figure
WindowButtonMotionFcn
End user moves the pointer within figure
the figure window.
WindowButtonUpFcn
End user releases a mouse button. figure
WindowKeyPressFcn
End user presses a key while the
pointer is on the figure or any of
its child objects.
10-6
figure
WindowKeyReleaseFcn
End user releases a key while the
pointer is on the figure or any of
its child objects.
figure
WindowScrollWheelFcn
End user turns the mouse wheel
while the pointer is on the figure.
figure
10
Code a Programmatic UI
function myui()
figure
uicontrol('Style','slider','Callback',@display_slider_value);
end
function display_slider_value(hObject,callbackdata)
newval = num2str(hObject.Value);
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
10-8
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.
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 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.
10-9
10
Code a Programmatic UI
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
it as an empty array. The following table lists the callbacks and components that use
callbackdata.
Callback Property Name
Component
WindowKeyPressFcn
WindowKeyReleaseFcn
WindowScrollWheel
figure
KeyPressFcn
KeyReleaseFcn
SelectionChangedFcn
uibuttongroup
CellEditCallback
CellSelectionCallback
uitable
Related Examples
More About
10-10
11
Manage Application-Defined Data
11
11-2
Method
Description
Store Data in
UserData or
Other Object
Properties on
page 11-3
Store Data
as Application
Data on page
11-7
Create Nested
Callback
Functions
(Programmatic
Method
UIs) on page
11-12
Description
Store Data
Using the
guidata
Function on
page 11-13
If you are using an earlier release, use the get and set functions instead:
hfig = figure;
figname = get(hfig,'Name');
set(hfig,'Name','My Window');
If your code does not have direct access to a component, use the findobj function to
search for that component. If the search is successful, findobj returns the component as
output. Then you can access the components properties.
The following UI code uses the UserData property to share information about the slider.
To see how it works, copy and paste this code into an editor and run it.
function my_slider()
11-3
11
hfig = figure();
slider = uicontrol('Parent', hfig,'Style','slider',...
'Units','normalized',...
'Position',[0.3 0.5 0.4 0.1],...
'Tag','slider1',...
'UserData',struct('val',0,'diffMax',1),...
'Callback',@slider_callback);
button = uicontrol('Parent', hfig,'Style','pushbutton',...
'Units','normalized',...
'Position',[0.4 0.3 0.2 0.1],...
'String','Display Difference',...
'Callback',@button_callback);
end
function slider_callback(hObject,eventdata)
sval = hObject.Value;
diffMax = hObject.Max - sval;
data = struct('val',sval,'diffMax',diffMax);
hObject.UserData = data;
% For R2014a and earlier:
% sval = get(hObject,'Value');
% maxval = get(hObject,'Max');
% diffMax = maxval - sval;
% data = struct('val',sval,'diffMax',diffMax);
% set(hObject,'UserData',data);
end
function button_callback(hObject,eventdata)
h = findobj('Tag','slider1');
data = h.UserData;
% For R2014a and earlier:
% data = get(h,'UserData');
display([data.val data.diffMax]);
end
When the user moves the slider, the slider_callback uses these commands to store
data in a structure:
data = struct('val',sval,'diffMax',diffMax) stores the values, sval and
diffMax, in a structure called data.
hObject.UserData = data stores the value of data in the UserData property of
the slider.
11-4
When the user clicks the push button, the button_callback uses these commands to
retrieve the data:
h = findobj('Tag','slider1') finds the slider component.
data = h.UserData gets the value of the sliders UserData property.
Share UserData in GUIDE UIs
To set up a GUIDE UI for sharing slider data with the UserData property, perform
these steps:
1
In the GUIDE Quick Start dialog box, select Blank GUI (Default). Then, click OK.
Click OK.
Select the push button tool from the component palette at the left side of the Layout
Editor and drag it into the layout area.
Select the slider tool from the component palette at the left side of the Layout Editor
and drag it into the layout area.
Select File > Save. Save the UI as myslider.fig. MATLAB opens the code file in
the Editor.
Set the initial value of the UserData property in the opening function,
myslider_OpeningFcn. This function executes just before the UI is visible to users.
In myslider_OpeningFcn, insert these commands immediately after the command,
handles.output = hObject.
data = struct('val',0,'diffMax',1);
set(handles.slider1,'UserData',data);
11-5
11
Add code to the slider callback for modifying the data. Add these commands to the
end of the function, slider1_Callback.
maxval = get(hObject,'Max');
sval = get(hObject,'Value');
diffMax = maxval - sval;
data = get(hObject,'UserData');
data.val = sval;
data.diffMax = diffMax;
% Store data in UserData of slider
set(hObject,'UserData',data);
11-6
data.val = sval;
data.diffMax = diffMax;
% Store data in UserData of slider
set(hObject,'UserData',data);
Add code to the push button callback for retrieving the data. Add these commands to
the end of the function, pushbutton1_Callback.
% Get UserData from the slider
data = get(handles.slider1,'UserData');
currentval = data.val;
diffval = data.diffMax;
display([currentval diffval]);
This code uses the handles structure to access the slider. The command, data =
get(handles.slider1,'UserData'), gets the sliders UserData property. Then,
the display function displays the stored values.
10 Save your code by pressing Save in the Editor Toolstrip.
11-7
11
The first input, obj, is the component object in which to store the data. The second input,
name, is a string that identifies the value. The third input, value, is the value you want
to store.
To retrieve application data, use the getappdata function:
data = getappdata(obj,name);
The component, obj, must be the component object containing the data. The second
input, name, must match the string you used to store the data. Unlike the UserData
property, which only holds only one variable, you can use setappdata to store multiple
variables.
Share Application Data in UIs Created Programmatically
This UI uses application data to share two values. To see how it works, copy and paste
this code into an editor and run it.
function my_slider()
hfig = figure();
setappdata(hfig,'slidervalue',0);
setappdata(hfig,'difference',1);
slider = uicontrol('Parent', hfig,'Style','slider',...
'Units','normalized',...
'Position',[0.3 0.5 0.4 0.1],...
'Tag','slider1',...
'Callback',@slider_callback);
button = uicontrol('Parent', hfig,'Style','pushbutton',...
'Units','normalized',...
'Position',[0.4 0.3 0.2 0.1],...
'String','Display Values',...
'Callback',@button_callback);
end
function slider_callback(hObject,eventdata)
diffMax = hObject.Max - hObject.Value;
setappdata(hObject.Parent,'slidervalue',hObject.Value);
setappdata(hObject.Parent,'difference',diffMax);
% For R2014a and earlier:
% maxval = get(hObject,'Max');
% currval = get(hObject,'Value');
% diffMax = maxval - currval;
% parentfig = get(hObject,'Parent');
11-8
% setappdata(parentfig,'slidervalue',currval);
% setappdata(parentfig,'difference',diffMax);
end
function button_callback(hObject,eventdata)
currentval = getappdata(hObject.Parent,'slidervalue');
diffval = getappdata(hObject.Parent,'difference');
% For R2014a and earlier:
% parentfig = get(hObject,'Parent');
% currentval = getappdata(parentfig,'slidervalue');
% diffval = getappdata(parentfig,'difference');
display([currentval diffval]);
end
When the user moves the slider, the slider_callback function calculates diffMax.
Then, it uses these commands to modify the application data:
setappdata(hObject.Parent,'slidervalue',hObject.Value) stores the
current slider value in the figure using the name, 'slidervalue'. In this case,
hObject.Parent is the figure.
setappdata(parentfig,'difference',diffMax) stores diffMax in the figure
using the name, 'difference'.
When the user clicks the push button, the button_callback function retrieves the data
using these commands:
currentval = getappdata(hObject.Parent,'slidervalue') retrieves the
current slider value from the figure. In this case, hObject.Parent is the figure.
diffval = getappdata(hObject.Parent,'difference') retrieve the
difference value from the figure.
Share Application Data in GUIDE UIs
To set up a GUIDE UI for sharing application data, perform these steps:
1
In the GUIDE Quick Start dialog box, select Blank GUI (Default). Then, click OK.
11
Click OK.
Select the push button tool from the component palette at the left side of the Layout
Editor and drag it into the layout area.
Select the slider tool from the component palette at the left side of the Layout Editor
and drag it into the layout area.
Select File > Save. Save the UI as myslider.fig. MATLAB opens the code file in
the Editor.
Set the initial value of the application data in the opening function,
myslider_OpeningFcn. This function executes just before the UI is visible to users.
In myslider_OpeningFcn, insert these commands immediately after the command,
handles.output = hObject.
setappdata(handles.figure1,'slidervalue',0);
setappdata(handles.figure1,'difference',1);
11-10
Add code to the slider callback for changing the data. Add these commands to the
end of the function, slider1_Callback.
maxval = get(hObject,'Max');
currval = get(hObject,'Value');
diffMax = maxval - currval;
% Store application data
setappdata(handles.figure1,'slidervalue',currval);
setappdata(handles.figure1,'difference',diffMax);
This callback function has access to the handles structure, so the setappdata
commands store the data in handles.figure1.
9
Add code to the push button callback for retrieving the data. Add these commands to
the end of the function, pushbutton1_Callback.
% Retrieve application data
currentval = getappdata(handles.figure1,'slidervalue');
diffval = getappdata(handles.figure1,'difference');
display([currentval diffval]);
11-11
11
This callback function has access to the handles structure, so the getappdata
commands retrieve the data from handles.figure1.
10 Save your code by pressing Save in the Editor Toolstrip.
11-12
end
The main function defines a struct array called data. When the user moves the slider,
the slider_callback function updates the val and diffMax fields of the data
structure. When the end user clicks the push button, the button_callback function
displays the values stored in data.
Note: Nested functions are not recommended for GUIDE UIs.
The first input, object_handle, is any UI component (typically hObject). The second
input, data, is the variable to store. Every time you call guidata using two input
arguments, MATLAB overwrites any previously stored data. This means you can only
store one variable at a time. If you want to share multiple values, then store the data as
a struct array or cell array.
To retrieve data, call guidata using one input argument and one output argument:
data = guidata(object_handle);
The component you specify to store the data does not need to be the same component that
you use to retrieve it.
If your data is stored as a struct array or cell array, and you want to update one
element without changing the other elements, then retrieve the data and replace it with
the modified array:
data = guidata(hObject);
data.myvalue = 2;
guidata(hObject,data);
11
The following code is a simple example of a programmatic UI that uses guidata to share
a structure containing two fields. To see how it works, copy and paste this code into an
editor and run it.
function my_slider()
hfig = figure();
guidata(hfig,struct('val',0,'diffMax',1));
slider = uicontrol('Parent', hfig,'Style','slider',...
'Units','normalized',...
'Position',[0.3 0.5 0.4 0.1],...
'Tag','slider1',...
'Callback',@slider_callback);
button = uicontrol('Parent', hfig,'Style','pushbutton',...
'Units','normalized',...
'Position',[0.4 0.3 0.2 0.1],...
'String','Display Values',...
'Callback',@button_callback);
end
function slider_callback(hObject,eventdata)
data = guidata(hObject);
data.val = hObject.Value;
data.diffMax = hObject.Max - data.val;
% For R2014a and earlier:
% data.val = get(hObject,'Value');
% maxval = get(hObject,'Max');
% data.diffMax = maxval - data.val;
guidata(hObject,data);
end
function button_callback(hObject,eventdata)
data = guidata(hObject);
display([data.val data.diffMax]);
end
When the user moves the slider, the slider_callback function executes these
commands to retrieve and modify the stored data:
data = guidata(hObject) retrieves the stored data as a structure.
data.diffMax = maxval - data.val modifies the diffMax field in the structure.
guidata(hObject,data) stores the modified structure.
11-14
When the user clicks the push button, the button_callback function calls guidata
to retrieve a copy of the stored structure. Then it displays the two values stored in the
structure.
Use guidata in GUIDE UIs
GUIDE uses the guidata function to store a structure called handles, which contains
all the UI components. MATLAB passes the handles array to every callback function.
If you want to use guidata to share additional data, then add fields to the handles
structure in the opening function. The opening function is a function defined near the top
of your code file that has _OpeningFcn in the name.
To modify your data in a callback function, modify the handles structure, and then store
it using the guidata function. This slider callback function shows how to modify and
store the handles structure in a GUIDE callback function.
function slider1_Callback(hObject, eventdata,handles)
% hObject
handle to slider1 (see GCBO)
% eventdata reserved - to be defined in a future version of MATLAB
% handles
structure with handles and user data (see GUIDATA)
% Hints: get(hObject,'Value') returns position of slider
%
get(hObject,'Min') and get(hObject,'Max') to determine range
handles.myvalue = 2;
guidata(hObject,handles);
end
To see a full example of a GUIDE UI that uses the guidata function, follow these steps
to copy and examine the code.
1
Set your current folder to one to which you have write access.
.
11-15
11
Set your current folder to one to which you have write access.
Display the UIs in two GUIDE Layout Editors with these commands:
guide changeme_main
guide changeme_dialog
Set your current folder to one to which you have write access.
Display the UIs in three GUIDE Layout Editors with these commands:
guide guide_iconeditor;
guide guide_toolpalette;
guide guide_colorpalette;
11-16
More About
Nested Functions
11-17
12
Manage Callback Execution
12
If the running callback contains one of these commands, then MATLAB stops the
execution of the running callback and executes the interrupting callback. MATLAB
resumes executing the running callback when the interrupting callback completes.
If the running callback does not contain one of these commands, then MATLAB
finishes executing the callback without interruption.
For more details about the interruptible property and its effects, see the Interruptible
property description on the Uicontrol Properties page.
Example
This example shows how to control callback interruption using the Interruptible and
BusyAction properties.
Copy the Source File
1
In MATLAB, set your current folder to one in which you have write access.
12-3
12
Clicking specific pairs of buttons demonstrates the effect of different property value
combinations :
12-4
Here is the command that creates the Wait (uninterruptible) push button. Notice that
the Interruptible property is set to 'off'.
h_nointerrupt = uicontrol(h_panel1,'Style','pushbutton',...
'Position',[30,40,120,30],...
'String','Wait (uninterruptible)',...
'TooltipString','Interruptible = off',...
'Interruptible','off',...
'Callback',@wait_uninterruptible);
Here is the command that creates the Surf Plot (queue) push button. Notice that the
BusyAction property is set to 'queue'.
hsurf_queue = uicontrol(h_panel2,'Style','pushbutton',...
'Position',[30,200,110,30],...
'String','Surf Plot (queue)',...
'BusyAction','queue',...
'TooltipString','BusyAction = queue',...
'Callback',@surf_queue);
12-5
12
Here is the command that creates the Mesh Plot (cancel) push button. Notice that the
BusyAction property is set to 'cancel'.
hmesh_cancel = uicontrol(h_panel2,'Style','pushbutton',...
'Position',[30,130,110,30],...
'String','Mesh Plot (cancel)',...
'BusyAction','cancel',...
'TooltipString','BusyAction = cancel',...
'Callback',@mesh_cancel);
See Also
Related Examples
More About
12-6
App Designer
13
App Designer Basics
Create Simple App Using App Designer on page 13-2
Open or Run App Designer Apps on page 13-5
Differences Between App Designer and GUIDE on page 13-6
Graphics Support in App Designer on page 13-11
13
13-2
From the App Designer Component Library on the left, press Ctrl and drag a
Slider component into the design area.
Tip Pressing the Ctrl key as you drag a component into the design area
suppresses automatic inclusion of a label with the component.
b
c
3
Replace the default label text by clicking the label text, Semicircular Gauge,
and then typing Slider Value.
Add a slider callback. Callbacks are functions that you code to respond to app user
interactions with app components.
In the central design area, right-click the slider and select Callbacks > Add
ValueChangedFcn callback.
Accept the default callback name by clicking OK in the Add Callback Function dialog
box.
Although not done here (to keep the example simple), changing the function name
makes it easier to associate the callback code with a component. This practice is
especially effective when there are multiple instances of the same component in an
app.
13-3
13
In the code view that opens, notice the default code in the SliderValueChanged
function.
value = app.Slider.Value;
Replace the default code with code that sets the semicircular gauge value to the
slider value.
To access or set a property value, specify app, the component, and the component
property name using dot notation.
Replace the default callback code with this code.
app.SemicircularGauge.Value = app.Slider.Value;
Click Run.
Save the app when prompted.
See Also
Code Response to Reflect Changing Slider Value on page 16-42 | Graphics Support
in App Designer on page 13-11
13-4
13-5
13
In GUIDE
In App Designer
Use the axes function and Use the uiaxes function and
Axes properties to access all UI Axes properties to plot 2the graphics functionality
D line and scatter plots only.
available in MATLAB.
Code Editability
13-6
Callback Arguments on
page 13-9
Component Creation on
page 13-10
Figure Support
In both GUIDE and App Designer, a figure window contains UI components. GUIDE
creates a figure window by calling the figure function. App Designer creates a UI figure
that is equivalent to the window created by the uifigure function.
Some functions that you can use with figure windows are not supported for use with
the UI figure window. In addition, some components are supported by only one type of
figure window. For details, see Graphics Support in App Designer on page 13-11
Axes Support
In both GUIDE and App Designer, you plot data using an axes component. GUIDE
calls the axes function to create an axes object. App Designer calls the uiaxes function
to create a UIAxes object. UIAxes objects support a subset of plotting functions and
features. For details, see Graphics Support in App Designer on page 13-11,
Code Structure
App Designer code has a different structure and characteristics from GUIDE code:
MATLAB file structure
App Designer code uses the MATLAB class structure, which is easy to read. App
properties appear first, followed by user-defined functions, and then the code used for
app initialization and component creation.
Integrated editor
You edit app code within App Designer using an integrated version of the MATLAB
Editor. The integrated editor includes features such as debugging, smart indenting,
and Code Analyzer indicators.
Code editing
To prevent you from accidentally overwriting code that App Designer manages,
some code is not editable. Uneditable code is indicated in the editor by a light gray
background. You can write and edit callback code, helper functions, and property
declarations that you create.
No default callback declarations
13-7
13
App Designer only creates a callback declaration when you explicitly request it. For
example, if you right-click a component in the canvas, and then select a callback
from the context menu, App Designer creates a callback declaration. This convention
prevents empty callback declarations from cluttering your code.
Default sample callback code
When you explicitly add a callback declaration, App Designer adds sample code to
the callback by default. When the app user triggers the callback by manipulating the
component in the running app, the sample code accesses a component property value.
The sample code provides an example of how to access a component and its properties
from within a callback. You can replace this code with code that is appropriate for
your app.
Note: App Designer does not generate sample callback code when you create a
callback for a button component.
Single file
App Designer creates a single MLAPP file that contains the information required to
display and run your app. There is no associated FIG file.
For details see, App Designer Code Generation on page 16-2.
As shown in the example, you always indicate that components are app object properties
by including app in the dot notation. For a complete example, see Create Simple App
Using App Designer on page 13-2.
Callback Configuration
GUIDE uicontrol components provide a Callback property that executes when the
app user interacts with each component in a typical way (such as clicking a button). Most
13-8
Callback Arguments
In GUIDE, all callback definitions pass hObject, eventdata, and a handles structure
as arguments.
In App Designer, all callback definitions specify app as an input argument instead
of hObject and a handles structure. All components are defined and accessed as
properties of the app object. Event data is passed only when it is not empty.
For example, compare the callback definition for a check box that assigns the state of the
check box to a variable, value.
In GUIDE, the check box callback definition is this:
function checkbox1_Callback(hObject,eventdata,handles)
value = get(hObject,'Value');
end
In App Designer, assuming the code name for the check box is CheckBox, the check box
callback definition is this:
function CheckBoxValueChanged(app)
value = app.CheckBox.Value;
end
Data Sharing
In GUIDE, to share data across callbacks, you can use the UserData property or the
guidata or setappdata functions.
13-9
13
In App Designer, to share data across callbacks, you create and use a property. For
example, suppose that you create the MyVal property to share a value across your app
callbacks. To set the property value, use dot notation:
app.MyVal = 15;
Then, if you want to set the Value property of a numeric edit field named Temp to the
MyVal property value use this code:
app.Temp.Value = app.MyVal;
When referencing app properties, including components, always use app in the dot
notation.
For more information and an example of data sharing using App Designer, see About
App Properties on page 16-19.
Component Creation
GUIDE creates most components with the uicontrol function, and you use uicontrol
properties to control component appearance and behavior. However, some uicontrol
properties are applicable to only a subset of components.
App Designer code uses a different function for creating each type of component. For
instance, uilistbox creates a list box and uislider creates a slider. Each component
provides a set of properties designed specifically for that type of component. For example,
when you select a slider in App Designer, the property editor and inspector present only
slider options. For more information, see Choose Components for Your App Designer
App on page 14-2 and Customize App Designer Components on page 14-11.
13-10
Graphics Support
If you are creating an app that displays graphics, you must specify the target UI figure or
UI axes when you call certain graphics functions. If you do not specify the target object,
MATLAB uses gcf or gca to determine the target object, and the result might not be
what you expected.
Furthermore, UI figures do not support most of the interactive functionality that
traditional figures support. For example, UI figures do not support panning, zooming,
mouse, or keyboard interactions.
The following table lists the graphics functions that UI figures and UI axes support in
R2016a. All other graphics functions are unsupported.
Category
13-11
13
Category
Coordinate
Systems
Utilities
Figures
xlim
ylim
xlabel
ylabel
grid
box
set
get
delete
findobj
reset
ishandle
isgraphics
newplot
ancestor
close
xlabel(app.UIAxes,'Frequency');
ax = findobj(app.UIFigure,'XLim',[0 1]);
f = uifigure;
close(f);
All other graphics functions that are not listed here are unsupported in App
Designer, UI figures, and UI axes.
UI axes support only a subset of the properties that traditional axes support. For
example, UI axes do not support lighting and camera properties or properties for
interactive control. For a full list of supported properties, see UI Axes (App Designer)
Properties.
UI figures support a different set of interactive components than traditional figures
do. For example, UI figures do not support uicontrols or uimenus. For a full list of
supported components, see Components in App Designer.
See Also
More About
13-13
14
Component Choices and
Customizations
Choose Components for Your App Designer App on page 14-2
Customize App Designer Components on page 14-11
14
Suggested Components
Button
Lamp
Gauge
Label
Graph Data
To graph data in a 2D line plot or scatter plot, use a UIAxes component. UIaxes
components support a subset of graphics functionality. For details, see Graphics Support
in App Designer on page 13-11.
14-2
14-3
14
As shown in some of the samples that follow, if the app user enters an invalid value, the
component flags the error. The component handles the error automatically and returns
the value to the previous setting. There is no need for you to code the validity checking.
The component does it for you.
Sample Spinners
As shown in some of the samples that follow, if the app user enters an invalid value, the
component flags the error. The component handles the error automatically and returns
the value to the previous setting. There is no need for you to code the validity checking.
The component does it for you.
14-4
Sample Knobs
14
Sample Switches
Requirement
Component to Consider
Discrete knob
14-7
14
14-8
Sample Gauges
Identify Components
To convey information, such as the type of values you want the app user to specify or the
units of measurement, use labels with other components.
Organize Components
To organize components into collections of components, use panels or tab groups.
Consider using tab groups when you want to conserve app space and the app user does
not need to see the content on multiple tabs concurrently.
Sample Panel
14-9
14
14-10
14-11
14
Changes you make are reflected in the app code (which you can view by clicking Code
View).
Set Property Values for Multiple Components Simultaneously
You can set many property values for multiple components simultaneously. For instance,
to make the font properties for all components that support font properties to be the
same, follow these steps.
1
In the design area, multiselect the components by holding down the Ctrl key and
clicking each component you want to select. Alternatively, left-click a blank spot
in the design area and drag a selection border around the components you want to
select.
Selecting a design group is the same as individually selecting the components
within the design group. For example, this image shows a selection that includes
a set of grouped buttons and an ungrouped button. For information on creating
design groups, see Group Components for Layout Tasks in App Designer on page
15-13.
14-12
In the property panel to the right of the design area, on the Configuration tab,
change the property values for the selected components.
Using the example from step 1, if you change the font style to bold in the property
panel, then the text on all buttons changes to bold.
Be aware that:
If you multiselect different types of components, then the properties presented on the
Configuration tab are a subset of frequently used properties that are common to all
the selected components.
For instance, if you multiselect a text edit field and a lamp in the design area, then
the only option presented on the Configuration tab is Enable.
14-13
14
If you multiselect components of the same type, then most properties on the
Configuration tab for that component are on display. The values presented in the
property editor are those of the anchor component. The anchor component has a filled
selection border. For example, the button labeled High in this image is the anchor
component.
14-14
In the design area, click the label text and type, This chart shows.
In the field to the right of a property name, specify or select a new value.
To view what a property affects and how to specify the property value, click the property
name or the property field.
The information appears at the bottom of the Inspector tab.
14-15
14
The only properties excluded from the inspector are Parent, Child and Callbacks. The
following table describes how to view and change these properties.
14-16
Task
What to Do
Task
What to Do
Change Parentand Child property values. Move components in design view. For
details, see Parent and Reparent
Components in App Designer on page
15-15
Add a callback function.
In the Component Browser panel, rightclick the component name, and then click
Callbacks > Go to > callback-functionname callback.
14-17
14
It is a best practice is to make sure that all components are completely within the design
area when you finalize your app design. If components are above or to the right of the
central design area at design time, the automatic resize behavior does not initiate when
resizing begins. Instead, it occurs only when the window is large enough to contain those
components entirely.
For example, suppose that the design area appears as shown. When you save and run
the app, automatic resizing is not initiated until the app window grows large enough to
enclose the button (on the upper right) completely.
Components that you place above or to the right of the design area might become visible
when the app user resizes the app window. If you have a good reason to keep components
14-18
there, but do not want the app user to be able to see them, disable the automatic resize
behavior.
Disable Automatic Resize Behavior
You can disable automatic resize behavior explicitly or implicitly.
To disable automatic resize behavior explicitly:
1
In the design area, select click the figure name in the Component Browser.
By default the component browser lists the figure as app.UIFigure.
14-19
14
Click More....
When the app runs, you cannot enter 5 in the field. However, you can enter any value
greater than 5, but less than or equal to 10.
Round Numeric Values
Spinners and numeric edit fields enable you to specify whether the displayed and stored
value is rounded to the nearest integer. In the case where a numeral has a fractional part
of 0.5, the value rounds to the integer with larger magnitude. For instance, 2.5 rounds
to 3 and-2.5 rounds to -3.
1
In the central design area, select the numeric edit field or spinner.
In the property panel, on the Configuration tab, under the Value category, click
More....
In the central design area, select the numeric edit field or spinner.
In the property panel, on the Configuration tab, scroll to the Display category.
Select Custom.
14
14-22
Goal
Steps
Reorder rows.
Visual
15
App Layout
Add and Delete Components Using App Designer on page 15-2
Move Components in App Designer on page 15-5
Align, Space, and Resize Components in App Designer on page 15-6
Group Components for Layout Tasks in App Designer on page 15-13
Parent and Reparent Components in App Designer on page 15-15
15
App Layout
To suppress default label inclusion, press and hold the Ctrl key as you drag the
component into the design area.
For information on grouping components, see Group Components for Layout Tasks in
App Designer on page 15-13.
Add Components
After adding components to the design area from the component library, add more
components using any of these methods:
Use a context menu option.
Right-click a single component or a set of multiselected components in the design
area, and then from the context menu, select Duplicate, Copy, or Paste.
Drag-duplicate a component.
While holding down the Ctrl key, left-click the component in the design area, and
then drag the duplicate to a new location within the current parent container. (On
Windows, you can also right-click and drag the duplicate component.)
15-2
Delete Components
Delete components using any of these methods:
Use a context menu option.
Right-click a single component or a set of multiselected components, and then from
the context menu, click Delete.
Use key combinations, as described in App Designer Keyboard Shortcuts on page
17-2.
Note: If you delete a component grouped with a label, App Designer deletes the label too.
Multiselect Components
Multiselect components using any of these methods:
In the design area, hold down the Ctrl or Shift key and click each component to
include in the selection.
Left-click a blank spot in the design area and drag a selection border around the
components you want to select.
Use key combinations, as described in App Designer Keyboard Shortcuts on page
17-2.
Note: You cannot multiselect tabs and you cannot multiselect components with different
parents.
15-3
15
App Layout
15-4
15-5
15
App Layout
Component Alignment
App Designer offers three techniques for positioning components:
Manual Alignment Using Alignment Hints on page 15-6
This method is useful when you want to arrange components in a visually appealing
way, but are not concerned about precise measurements.
Manual Alignment Using a Grid on page 15-7
This method is useful when you want to position components at precise locations
for instance 30 pixels from the edge of the figure window.
Automatic Component Alignment on page 15-9
This method is useful for refining positioning after positioning components using
alignment hints.
Manual Alignment Using Alignment Hints
By default, as you drag components in the design area, you see alignment hints that
assist you in arranging the components.
15-6
15-7
15
App Layout
Goal
Instructions
Note: You cannot enable the snap to grid feature unless Show grid is selected.
15-8
Right-click the component with which you want the others to align, and then select
an Align option.
In this image, button C is the component with which buttons A and B will align. Notice
that App Designer indicates this state by enclosing button C in a heavier weight border
than the other components.
If you left align the components, they align along the left side of button C.
The component with which other components align is the anchor component. The
technique you use to select components determines which component is the anchor:
If you select components using Ctrl + Click, then the last component you select is the
anchor component.
15-9
15
App Layout
If you drag-select components, then the last component you include in the drag
rectangle is the anchor component.
If you press Ctrl + A to select all components, then the last component you add to the
design area is the anchor component. If the last component added is a direct child of
the UI figure and is grouped, then the group is the anchor.
A group of components behaves as though it is a single component with respect to
alignment and spacing operations.
Space Components
You can direct App Designer to space components automatically, or you can specify
spacing values. Both approaches are presented in these steps:
1
In the design area, select the components that you want to space.
Select two or more components to space manually. Select three or more components
to space automatically.
Select the direction in which you want to apply spacing by clicking a spacing
application option, Apply horizontally or Apply vertically.
If you selected Autospacing, App Designer evenly distributes the spacing
equally among the selected components in the selected direction.
If you specified the number of pixels, App Designer applies the spacing among the
selected components as you specified in the selected direction.
Sometimes, the number of pixels between the two components prevents App
Designer from making the space between each component identical. However, the
spacing difference is never more than one pixel.
15-10
Although you can resize the components within a group, you cannot resize a group
directly. The group automatically adjusts as you change the size or position of the
components within it.
This table summarizes features that can make resizing components easier and faster.
Goal
Instructions
15
App Layout
Goal
Instructions
the aspect ratio for components with a
built-in aspect ratio. (Such components
have 4 resize handles.) In addition, App
Designer always maintains the height of a
slider.
For more keyboard shortcuts, see Component Resize Shortcuts on page 17-5.
For information on controlling run-time component resizing, see Set Window and
Component Resize Behavior on page 14-17.
15-12
By default, when you drag a component, such as an edit field, from the Component
Library into the design area, the component and its associated label component are
added to the design area as a design group. Select a design group by clicking one of the
components in the group or the empty area between components in the group.
Design groups are design-time constructs only. They are not represented in the generated
code nor seen in a running app.
Note: Do not confuse design groups with components that have the word group in their
name, such as button groups, radio button groups, and tab groups.
15-13
15
App Layout
15-14
You can nest instances of the same container component, except for UI figures. For
example, one panel can be the parent of another panel.
You can view the component parent-child relationships in the Component Browser.
15-15
15
App Layout
To change the parent of one component within a group of components, ungroup the
components, and then drag the component to the new parent.
For information about creating component groups and ungrouping components, see
Group Components for Layout Tasks in App Designer on page 15-13. Do not confuse
grouped components with these container components that App Designer provides:
radio button groups, toggle button groups, and tab groups.
15-17
16
App Programming
App Designer Code Generation on page 16-2
Rename Components, Properties, Callbacks, and Functions in App Designer on page
16-5
App Designer Callbacks on page 16-8
App Designer Startup Function on page 16-10
Detect and Correct Coding Errors Using App Designer on page 16-13
Share Data Across Callbacks in App Designer on page 16-19
Code and Call App Functions in App Designer on page 16-24
Delete Code from the App Designer Editor on page 16-29
Simple Example Apps for App Designer on page 16-31
16
App Programming
16-2
16-3
16
App Programming
Notice that:
The first section of code defines the app properties.
Initially, this section contains the properties that correspond to the app and the app
components. If you add properties to share data, App Designer adds your properties to
this region. For information on adding properties, see Share Data Across Callbacks
in App Designer on page 16-19.
The second section of code contains the app functions.
Initially, this section contains the framework for the startup function. If you add
callbacks or utility functions to the app, App Designer adds them to this region. For
information on adding functions, see Code and Call App Functions in App Designer
on page 16-24 andApp Designer Callbacks on page 16-8.
The third section of code initializes and creates the app and its components.
If you use App Designer property sheets or the Inspector to change component
property values, those changes appear in this section of the code. For information on
adding and customizing components, see Add and Delete Components Using App
Designer on page 15-2 and Customize App Designer Components on page 14-11.
If you rename code elements, as described in Rename Components, Properties,
Callbacks, and Functions in App Designer on page 16-5, App Designer updates the
name in the read-only and read-write areas of the code.
16-4
16
App Programming
You cannot change the app. prefix. All app component names must have the app.
prefix in code.
Tip If you are unsure which name corresponds to a particular component, use the
App Layout panel. By default, App Layout appears in the lower left corner of code
view.
Click the component that you want to identify. App Designer highlights the name of
that component in the code view Component Browser.
In the Code Browser (to the left of the editor, by default), click the tab that
corresponds to the element you want to rename.
The tabs are labeled Callbacks, Functions, and Properties.
16-6
App Designer updates the code to reflect the new name and all references to it when
you press Enter or click away from the edit field.
16-7
16
App Programming
Tip If a component does not support callbacks, the Callbacks option does not appear on
the context menu for that component.
Then, follow these steps:
1
16-8
In the Add Callback Function dialog box, enter a name for your callback function.
A best practice is to specify a name for the callback, rather than accept the
default name. This practice enables you to identify the control with which the
callback is associated and what the callback does. For instance, if you intend for a
button push to result in data being graphed, consider naming the button callback
GraphButtonPushed.
2
Click OK.
App Designer opens code view with the cursor placed in the newly created callback
function, below a line of sample code.
Note: Sample code is not included when you add a callback for a push-button
component.
Modify or replace the sample code with the code that you want MATLAB to run
when the app user interacts with the control.
Specify components and their properties using app. as a prefix for each component.
This practice makes it possible to access properties directly using dot notation. For
example, to set the Enable property of a button named GraphButton to 'off', use
the following code:
app.GraphButton.Enable = 'off';
App Designer Coding Tips on page 16-16 describes ways that App Designer
facilitates adding property names to your code.
4
For examples, see Simple Example Apps for App Designer on page 16-31.
Note: Multiple components cannot share a callback. If you want to share code among
callbacks, consider writing a utility function and calling it from multiple callbacks, as
described in Code and Call App Functions in App Designer on page 16-24.
16-9
16
App Programming
16-10
In App Designer:
1
In design view, drag an Axes (Line and Scatter) from the Component Library
into the central design area.
16
App Programming
To specify the data and plot it in the line plot, add this code.
d = [2 3; 4 5; 2 8; 7 5];
plot(app.UIAxes, d);
16-12
Notice that the MATLAB Code Analyzer indicators (orange wavy line and highlighting
on NumericEditField) also appear. When you change NumericEditField to
app.NumericEditField, both the coding alert and the Code Analyzer indicators
disappear.
If you want to suppress coding alerts, on the Editor tab, in the View section, clear
Enable app coding alerts.
16-13
16
App Programming
Adjusting your code in response to these messages can keep your code free of warnings
and errors. If you allow errors and warnings to accumulate, it can be more difficult to
debug your code later.
The App Designer editor does not provide all the Code Analyzer features that the
MATLAB Editor does. For instance:
Messages indicators do not appear in a column to the right of the code.
Message details are not available.
Adjusting Code Analyzer preferences has no effect on the App Designer editor.
The message for the most-recently thrown error opens automatically. To close it, click the
icon. To open a different error, click that icon.
16-14
To clear the error alert, correct the error, and then rerun you app. Make sure that no new
errors are revealed. Many errors are revealed only when a code branch runs, such as a
particular case in a switch statement. So test your app thoroughly.
Step through a file, pausing at points where you want to examine values.
After you set one or more breakpoints and click Run, MATLAB starts running the
code. When MATLAB hits a breakpoint, the Editor tab displays the Continue, Step,
Step In, Step Out, and Quit Debugging buttons.
If you step into a function that is in a file outside of your app, MATLAB opens the
function file in the MATLAB Editor. It places the cursor at the first executable line of
code.
View variable values in the MATLAB Workspace browser.
Clear a breakpoint by clicking it.
For details on these debugging features, see Debug a MATLAB Program.
16-15
16
App Programming
Place the cursor in a writable area of the App Designer editor where you want the
name to appear.
Drag the name from the Component Browser and drop it into the editor.
The name drops at the cursor location.
16-16
16-17
16
App Programming
16-18
Properties that you create to share data within and outside your app
This property is a public property that you define using App Designer. For instance,
suppose that you create a property to hold the result of a calculation that an app
function performs. You want to make it possible for the app user to perform additional
analysis on the result, outside the current app. Public properties are available in the
MATLAB workspace while the app is running.
For an example, see Share Data Among Multiple UI Figure Windows.
App Designer creates component properties. These are properties that control the display
and behavior of a component. You can modify the property values, but you cannot create
these properties. For instance, App Designer creates the Text property when you add
a text edit field to the design area. You cannot change the property name, but you can
change this property value.
16-19
16
App Programming
Hold down the Ctrl key and drag a Numeric Edit Field from the Component
Library into the central design area.
Holding down the Ctrl key prevents a label component from being added with the
edit field.
On the Editor tab click Property > Insert Private Property and replace the
highlighted word, Property with Counter.
Note: If you code contains errors, the Property button is disabled. For information
on debugging, see Detect and Correct Coding Errors Using App Designer on page
16-13.
16-20
In the Component Browser, right-click app.Button and select Callbacks > Add
ButtonPushedFcn callback.
In the Add Callback Function dialog box, click OK. (Accept the default callback
function name.)
Add code to increment the counter and display the Counter property value in the
numeric edit field each time the app user clicks the push button.
In the ButtonButtonPushed function, type:
app.Counter = app.Counter + 1;
app.NumericEditField.Value = app.Counter;
16
App Programming
Drag a Button and an Edit Field (Numeric) including a label, from the
Component Library into the central design area.
Double-click the numeric edit field label and change the text to Value:.
Double click the button text and change it to Calculate and Send.
Next, Lay out and code the app to plot the results of the calculation:
1
Drag a Button from the Component Library to the bottom of the central design
area.
Drag an Axes (Line and Scatter) from the Component Library into the central
design area.
11 In the Component Browser, right-click app.Button and select Callbacks > Add
ButtonPushedFcn callback, and then click OK.
12 Add this code to the ButtonButtonPushed callback function:
y = app.Data;
plot(app.UIAxes,y);
In the Component Browser, right-click app.Button and select Callbacks > Add
ButtonPushedFcn callback. Click OK to accept the default callback name.
The code calculates the value to be plotted. It then, calls the second app, and
specifies the value calculated in the first app as the Data property value for the
second app.
Run and test calcandsend.mlapp:
In the Value field, enter a numeric value, and then press Calculate and Send.
When the second app opens, click Plot. The data sent from the first app is plotted in the
second app.
16-23
16
App Programming
16-24
On the Editor tab, click the Function down arrow, and then select Insert Private
Function or Insert Public Function.
Unless you intend to use the function outside the current app, choose Add Private
Function.
2
App Designer adds the framework for your function above the app startup function.
Except for the access specification, the framework for private and public functions is
identical.
The first time you add a private function, App Designer creates a private method
block. If you add additional private functions, they are added to this method block.
Similarly, App Designer creates a public method block the first time you add a public
function to your app.
3
Replace the highlighted text, func, with a meaningful name for your function.
Optionally, replace results with one or more output arguments and add additional
input arguments. For example:
methods (Access = private)
function [a b] = PopulationEst(app,c)
end
end
If your function does not require output or return a value, you can delete the
results = syntax from the function declaration.
5
16-25
16
App Programming
Run your code and debug it, if needed, as described in Detect and Correct Coding
Errors Using App Designer on page 16-13.
Create and Call a Private Utility Function
This example shows how to share a private utility function throughout an app. It uses
a private function, mycalc, to calculate the sum and product of two values specified by
the app user. When the app user changes either value, the app recalculates the sum and
product by calling the mycalc function.
In App Designer:
1
Drag four numeric edit fields (and labels) from the Component Library on the left
of App Designer into the design area. Arrange and customize them as shown in the
preceding image and described in the table that follows. By default, when you drag a
numeric edit field into the design area, an associated label is also added to the design
area.
To rename a component, select it in the design area, double-click the current
component name in the Component Browser, and then type a new name.
Component
Label
Value 1:
Value1
16-26
None
Component
Label
Value 2:
Value2
None
Sum:
Sum
Editable: no
Product:
Product
Editable: no
Create a function to calculate the sum and the product of the values that the app
user enters for value 1 and value 2:
a
Replace the blue highlighted text, func, with a meaningful name for this
function, mycalc.
Code the function to get the app-user-entered values, perform calculations, and
assign values to the function output arguments, sum and product.
The function appears as follows:
function mycalc(app)
a = app.Value1.Value;
b = app.Value2.Value;
sum = a+b;
prod = a*b;
app.Sum.Value = sum;
app.Product.Value = prod;
end
Code the callback for the Value1 numeric edit field to call the mycalc function
whenever the app user changes the field value:
a
16
App Programming
Code the callback for the Value2 numeric edit field to call the mycalc function
whenever the app user changes the field value:
a
Test the app by entering numbers in the Value 1 and Value 2 fields and then clicking
away from the fields.
Then the plotStats app can call the stats function defined getInput by using a
command such as this:
results = app.getdata.stats
16-28
App Designer updates the code to remove the deleted component and its associated label
component, if one exists. App Designer also removes the component and its label from
design view.
Note: When you delete a component, callbacks created for that component are not
deleted. Therefore, the code you wrote for the callback is preserved.
16-29
16
App Programming
If you do not want to keep the callback code, in the Code Browser on the Callbacks
tab, right-click the callback function name. Then, select Delete from the context menu.
Similarly, to delete utility functions and properties you created, in the Code Browser on
the Functions or Properties tab, right-click the function or property name. Then, select
Delete from the context menu.
16-30
16-31
16
App Programming
In App Designer, from the Component Library on the left, drag an Axes (Line
and Scatter) component, an Edit Field (Numeric) component, and a Button
component into the central design area.
16-32
In the design area, double-click the Edit Field text and type Value.
In the design area, click the Button text and type Plot.
In the Component Browser, to the right of the editor, right-click app.Button and
select Callbacks > Add ButtonPushedFcn callback.
In the Add Callback Function dialog box, click OK. (Accept the default callback
function name.)
Add this code to the callback function. The code uses the value of the numeric edit
field in calculations and plots the results.
x = 0:pi/100:2*app.NumericEditField.Value;
y = sin(2*x);
plot(app.UIAxes,x,y);
Test the app by typing a number in the Value field, and then clicking Plot.
16-33
16
App Programming
16-34
In App Designer, from the Component Library on the left, drag an Axes (Line
and Scatter) into the central design area.
While holding down the Crtl key, drag a Drop Down into the central design area.
Holding down the Crtl key as you drag a component from the component library
prevents App Designer from adding a label component along with the drop-down
component.
Resize the axes component, and then arrange the components as shown in the
preceding image.
Do not be concerned with axes labels or drop-down component text in this step.
Select the axes in the design area. Then, in the Axes (Line and Scatter)
Properties panel to the right of the design area, clear the Title, X Label, and Y
Label fields.
16-35
16
App Programming
In the design area, resize the drop-down component to make it slightly wider.
(Otherwise the Line and Scatter Plot string will be clipped in the running
app.)
Tip To make the drop-down component the same size as shown in this example, on
the toolstrip Canvas tab, select Show resizing hints.
.
When you widen the drop-down component, App Designer displays the width in
pixels. The width used in this example is 110 pixels.
16-36
In the code editor, replace the highlighted word Property with the property name,
xdata.
When you refer to the property in a function, use dot notation, app.xdata.
12 Create a callback to control what the app does when an app user makes a selection
from the drop-down component.
In the Component Browser, right-click app.DropDown and select Callbacks >
Add ValueChangedFcn callback.
16-37
16
App Programming
13 In the Add Callback Function dialog box, click OK. (Accept the default callback
function name.)
App Designer adds sample code value = app.DropDown.Value; to the
DropDownValueChanged function.
14 Update the callback code so it appears as follows. This code gets the option that
the app user selected from the drop-down component, and then plots the data
accordingly. The hold function keeps the scatter plot from replacing the line plot.
value = app.DropDown.Value;
if strcmp(value,'Line')
plot(app.UIAxes,app.xdata,app.ydata);
elseif strcmp(value,'Scatter')
scatter(app.UIAxes, app.xdata, app.ydata);
else
plot(app.UIAxes,app.xdata,app.ydata);
hold(app.UIAxes,'on');
scatter(app.UIAxes, app.xdata, app.ydata);
end
16-38
Test the app by selecting different options from the drop-down component.
16-39
16
App Programming
In App Designer, from the Component Library on the left, drag the components
described in the following table into the central design area. Arrange the components
as shown in the preceding image. Use the property sheet to the right of the design
area to set component property values. By default, a label component is added when
you drag an edit field into the design area. The Label column indicates the text to
use for the label component associated with each edit field component that you add.
Component
Property to Set
UIAxesFreq
Not applicable
Title: Frequency
UIAxesTime
Not applicable
Title: Time
Edit Field
(Numeric)
NumericEditFieldf1 f1
Maximum: 500
Edit Field
(Numeric)
NumericEditFieldf2 f2
Maximum: 500
EditFieldTime
Not Applicable
Button
Button
Not Applicable
Text: Plot
Tip To change the code name for a component, double-click the current component
name in the Component Browser, and then type the new name.
16-40
In the Add Callback Function dialog box, click OK. (Accept the default callback
function name.)
App Designer opens code view.
Get the input values, perform calculations, and plot the data in the appropriate axes.
Add this code to function ButtonButtonPushed.
% Get app user input
f1 = app.NumericEditFieldf1.Value;
f2 = app.NumericEditFieldf2.Value;
t = str2num(app.EditFieldTime.Value);
%
x
y
m
f
Calculate data
= sin(2*pi*f1*t) + sin(2*pi*f2*t);
= fft(x,512);
= y.*conj(y)/512;
= 1000*(0:256)/512;
16-41
16
App Programming
Test the app by trying the various app controls in the running app.
The numeric edit fields, f1 and f2, display an error message if you enter a
nonnumeric value or one that falls outside the limits that you set.
This automatic input validation is an advantage to using a numeric edit field, rather
than a text edit field to get numeric input.
The edit field for the time vector does not prevent you from entering an invalid vector.
To handle invalid time vector values, define a ValueChangedFcn callback function
for the EditFieldTime component. Then code it to determine if the app users input
is valid.
16-42
In App Designer, while holding down the Ctrl key, drag a Slider and a
Semicircular Gauge from the Component Library into the central design area.
Arrange the components as shown in the preceding image.
Tip Holding down the Crtl key as you drag a component from the component library
prevents App Designer from adding a label component along with the component you
drag in.
16-43
16
App Programming
16-44
In the central design area, right-click the slider and select Callbacks > Add
ValueChangingFcn callback.
In the Add Callback Function dialog box, click OK. (Accept the default callback
function name.)
Code the callback to update the edit field when the app user drags the slider.
When the app user drags the slider, MATLAB generates event data and stores it in
the slider event Value property. You can query the event data using dot notation.
Replace the defaultSliderValueChanging callback code, changingValue =
event.Value;, with the following code:
app.SemicircularGauge.Value = event.Value;
16-45
16
App Programming
In App Designer, drag a Radio Button Group and a Lamp from the Component
Library into the central design area. By default, a label is added with the lamp.
Arrange and customize the components as shown in the preceding image and
described in this table. Use the property sheet to the right of the design area to set
property values.
Component
Name in Code
Property to Set
ButtonGroup (default)
Title: Indicator
RadioButton
StopRadioButton
Text: Stop
RadioButton
CautionRadioButton
Text: Caution
RadioButton
GoRadioButton
Selected: Yes
Text: Go
Lamp
Lamp (default)
Not applicable
Label
Label (default)
Text: Status
Tip To change the code name for a component, double-click the current component
name in the Component Browser, and then type the new name.
16-46
In the Add Callback Function dialog box, click OK. (Accept the default callback
function name.)
Code view opens.
Specify code to determine which radio button is selected, and then set the lamp color
accordingly.
Replace the default code in the ButtonGroupSelectionChange function with this
code. The code changes the lamp color depending on the radio button selected by the
app user.
16-47
16
App Programming
switch app.ButtonGroup.SelectedObject
case app.GoRadioButton
app.Lamp.Color = 'green';
case app.CautionRadioButton
app.Lamp.Color = 'yellow';
case app.StopRadioButton
app.Lamp.Color = 'red';
end
16-48
In App Designer, hold down the Ctrl key as you drag a Slider from the Component
Library into the central design area.
Holding down the Ctrl key prevents a label component from being added with the
slider.
16-49
16
App Programming
16-50
In the Add Callback Function dialog box, click OK. (Accept the default callback
function name.)
This code gets the UI Figure window width and height after a resize operation
and updates the location and size of the slider to keep it centered in the window.
The slider will be 30 pixels from the left and right sides of the window. The code
subtracts the slider height (6 pixels) from the window height and divides by 2. The
code subtracts 60 from the window width to account for 30 pixels on either side of the
slider.
7
16-51
16
App Programming
Note: Code you specify for the figure SizeChangedFcn callback takes precedence over
the resize behavior you select in design view with the UIFigure Properties panel.
16-52
17
Keyboard Shortcuts
17
Keyboard Shortcuts
Key or Keys
F5
Ctrl+S
Ctrl+O
Ctrl+Z
Shift + F7
If debugging is in progress, this shortcut
does not change the view.
Ctrl+Q
17-2
Action
Key or Keys
Action
Key or Keys
Shortcut
Add component only to central design area. Hold down the Ctrl key, click the
component, and drag it from the
Component Library on the left into the
design area.
17-3
17
Keyboard Shortcuts
Key or Keys
Tab
Shift+Tab
Ctrl+A
Ctrl+A
Key or Keys
Ctrl+G
Ctrl+Shift+G
17-4
Action
Key or Keys
Down Arrow
Left Arrow
Action
Key or Keys
Right Arrow
Move up 1 pixel.
Up Arrow
Shift+Down Arrow
Shift+Left Arrow
Shift+Right Arrow
Move up 10 pixels.
Shift+Up Arrow
Escape
Key
Resize component while maintaining aspect Press and hold down the Shift key before
ratio.
you begin to drag the component expander.
Resize component while keeping center
location unchanged.
Escape
Key or Keys
Ctrl+C
Ctrl+D
Ctrl+X
Ctrl+V
17-5
17
Keyboard Shortcuts
Action
Key or Keys
container component (panel, tab, or button
group). Radio buttons and toggle buttons
can only be pasted into radio button groups
or toggle button groups, respectively.
Design Area Grid Shortcuts
Action
Keys
Alt+G
Alt+P
Alt+Page Up
Alt+Page Down
Keys
Ctrl+Alt+1
Ctrl+Alt+2
Ctrl+Alt+3
Ctrl+Alt+4
Ctrl+Alt+5
Ctrl+Alt+6
17-6
Action
Key or Keys
Ctrl+B
Action
Key or Keys
Ctrl+[
Ctrl+]
Font size steps are: 8, 9, 10, 11, 12, 14, 16, 18, 20, 22, 24, 26, 28, 36, 48, 72.
Key or Keys
Ctrl+I
Ctrl+]
Ctrl+[
Key or Keys
Ctrl+X
Ctrl+C
Ctrl+V
17-7
17
Keyboard Shortcuts
Key or Keys
Find.
Ctrl+F
Find next.
F3
Find previous.
Shift+F3
Find selection.
Ctrl+F3
17-8
Action
Key or Keys
Ctrl+R
Evaluate selection.
F9
Open selection.
Ctrl+D
Ctrl+G
F12
App Packaging
18
Packaging GUIs as Apps
Apps Overview on page 18-2
Package Apps on page 18-5
Modify Apps on page 18-8
Share Apps on page 18-9
MATLAB App Installer File mlappinstall on page 18-10
Dependency Analysis on page 18-11
18
Apps Overview
What Is an App?
A MATLAB app is a self-contained MATLAB program with a user interface that
automates a task or calculation. All the operations required to complete the task
getting data into the app, performing calculations on the data, and getting results are
performed within the app. Apps are included in many MATLAB products. In addition,
you can create your own apps. The Apps tab on the MATLAB Toolstrip displays all
currently installed apps when you click the down arrow on the far right of the toolstrip.
Note: You cannot run MATLAB apps using the MATLAB Runtime. Apps are for
MATLAB to MATLAB deployment. To run code using the MATLAB Runtime, the code
must be packaged using MATLAB Compiler.
Apps Overview
You can share your app directly with other users, or share it with the MATLAB
user community by uploading it to the MATLAB File Exchange. When others install
your app, they do not need to be concerned with the MATLAB search path or other
installation details.
Watch this video for an introduction to creating apps:
Packaging and Installing MATLAB Apps (2 min, 58 sec)
Add-Ons
Apps (and other files) uploaded to the MATLAB File Exchange are available from
within MATLAB:
1
On the Home tab, in the Environment section, click the Add-Ons arrow
button.
18-3
18
18-4
Package Apps
Package Apps
Package apps you create into an app package for sharing with others. When you create
an app package, MATLAB creates a single app installation file (.mlappinstall). The
installation file enables you and others to install your app and access it from the apps
gallery without concern for installation details or the MATLAB path.
Note: As you enter information in the Package Apps dialog box, MATLAB creates and
saves a .prj file continuously. A .prj file contains information about your app, such
as included files and a description. Therefore, if you exit the dialog box before clicking
the Package button, the .prj file remains, even though a .mlappinstall file is not
created. The .prj file enables you to quit and resume the app creation process where you
left off.
To create an app installation file:
1
On the desktop Toolstrip, on the Home tab, click the Add-Ons down-arrow.
In the Package App dialog box, click Add main file and specify the file that you use
to run the app you created.
The main file must be callable with no input, and must be a function or method, not
a script. MATLAB analyzes the main file to determine other MATLAB files on which
the main file depends. For more information, see Dependency Analysis on page
18-11.
Tip The main file must return the figure handle of your app for MATLAB to remove
your app files from the search path when users exit the app. For more information,
see What Is the MATLAB Search Path?
(Functions created by GUIDE return the figure handle.)
Add additional files required to run your app, by clicking Add files/folders.
Such files are data, image, and other files that were not included via dependency
analysis.
18-5
18
You can include external interfaces, such as MEX-files, ActiveX, or Java in the
.mlappinstall file, although doing so can restrict the systems on which your app
can run.
5
In the Description field, describe your app so others can decide if they want to
install it.
After you create the package, when you select a .mlappinstall file in the Current
Folder browser, MATLAB displays the information you provided (except your
email address and company name) in the Current Folder browser Details panel.
If you share you app in the MATLAB Central File Exchange, the same information
also displays there. The screen shot you select, if any, represents your app in File
Exchange.
6
Click Package.
As part of the app packaging process, MATLAB creates a .prj file that contains
information about your app, such as included files and a description. The .prj
file enables you to update the files in your app without requiring you to respecify
descriptive information about the app.
18-6
In the Build dialog box, note the location of the installation file (.mlappinstall),
and then click Close.
Package Apps
18-7
18
Modify Apps
When you update the files included in a .mlappinstall file, you recreate and overwrite
the original app. You cannot maintain two versions of the same app.
To update files in an app you created:
1
In the Current Folder browser, navigate to the folder containing the project file
(.prj) that MATLAB created when you packaged the app.
By default, MATLAB writes the .prj file to the folder that was the current folder
when you packaged the app.
From the Current Folder browser, double-click the project file for your app package,
appname.prj
The Package App dialog box opens.
Adjust the information in the dialog box to reflect your changes by doing any or all of
the following:
If you made code changes, add the main file again, and refresh the files included
through analysis.
If your code calls additional files that are not included through analysis, add
them.
If you want anyone who installs your app over a previous installation to be
informed that the content is different, change the version.
Version numbers must be a combination of integers and periods, and can include
up to three periods 2.3.5.2, for example.
Anyone who attempts to install a revision of your app over another version is
notified that the version number is changed. The user can continue or cancel the
installation.
If your changes introduce different product dependencies, adjust the product list
in the Products field.
18-8
Click Package.
Share Apps
Share Apps
To share your app with others, give them the .mlappinstall file. All files you
added when you packaged the app are included in the .mlappinstall file. When the
recipients install your app, they do not need to be concerned with the MATLAB path or
other installation details. The .mlappinstall file manages that for them.
You can share your app with others by attaching the .mlappinstall file to an email
message, or using any other method you typically use to share files.
If you upload your app to MATLAB Central File Exchange, your users can download the
app from within MATLAB, as follows:
1
In MATLAB, on the Home tab, in the Environment section, click the Add-Ons
arrow button.
Provide instructions on installing your app by referring your users to Install an Add-On
Manually.
Note: While .mlappinstall files can contain any files you specify, MATLAB Central
File Exchange places additional limitations on submissions. Your app cannot be
submitted to File Exchange when it contains any of the following:
MEX-files
Other binary executable files, such as DLLs or ActiveX controls. (Data and image files
are typically acceptable.)
18-9
18
18-10
Dependency Analysis
Dependency Analysis
When you create an app package, MATLAB analyzes your main file and attempts to
include all the MATLAB files that it uses in the app package. However, MATLAB does
not guarantee to find every dependent file. MATLAB does not find files for functions that
your code references as strings (for instance, as arguments to eval, feval, and callback
functions). In addition, MATLAB can include some files that the main file never calls
when it runs.
Dependency analysis searches for executable files, such as:
MATLAB files
P-files
.fig files
MEX-files
Dependency analysis does not search for data, image, or other binary files, such as Java
classes and .jar files. Add such files manually when you package your app. The Package
Apps dialog box provides an option for doing so.
18-11