MATLAB®Creating Graphical User InterfacesR2015a
x ContentsRun the Program . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 9-4How Close Confirmation Dialogs Work . . . . . . . . . . . . . 9
6 Lay Out a UI Using GUIDE6-14Component Icon Description“Push Button”on page 6-25Push buttons generate an action when clicked. Forexample, an OK butto
GUIDE Components6-15Component Icon Description“Toggle Button”on page 6-41Toggle buttons generate an action and indicate whetherthey are turned on or
6 Lay Out a UI Using GUIDE6-16Component Icon Description“ActiveXComponent” onpage 6-65ActiveX components enable you to display ActiveX controlsin your
Add Components to the GUIDE Layout Area6-17Add Components to the GUIDE Layout AreaIn this section...“Place Components” on page 6-17“User Interface Co
6 Lay Out a UI Using GUIDE6-18Once you have defined a UI component in the layout area, selecting it automaticallyshows it in the Property Inspector. I
Add Components to the GUIDE Layout Area6-19Use Coordinates to Place ComponentsThe status bar at the bottom of the GUIDE Layout Editor displays:• Curr
6 Lay Out a UI Using GUIDE6-20If you select a single component and move it, the first two elements of the position vector(distance from left, distance
Add Components to the GUIDE Layout Area6-21Note Assign a unique identifier to each component in your panel or button group bysetting the value of its
6 Lay Out a UI Using GUIDE6-22Include Existing Components in Panels and Button GroupsWhen you add a new component or drag an existing component to a p
Add Components to the GUIDE Layout Area6-23Tip You need to move controls with the mouse to register them with the surroundingpanel or button group, e
xiDesign the 3-D Globe UI . . . . . . . . . . . . . . . . . . . . . . . 9-69Graphics Techniques Used in the 3-D Globe UI . . . . . . 9-74Automatically
6 Lay Out a UI Using GUIDE6-24To define user interface controls, you must set certain properties. To do this:1Use the Property Inspector to modify the
Add Components to the GUIDE Layout Area6-25Property Value DescriptionMax Scalar. Default is 1. Maximum value.Interpretation depends on thetype of com
6 Lay Out a UI Using GUIDE6-26• Specify the push button label by setting the String property to the desired label, inthis case, Button 1.To display th
Add Components to the GUIDE Layout Area6-27• If you want to set the position or size of the component to an exact value, then modifyits Position prop
6 Lay Out a UI Using GUIDE6-28• Specify the range of the slider by setting its Min property to the minimum value ofthe slider and its Max property to
Add Components to the GUIDE Layout Area6-29• If you want to set the location or size of the component to an exact value, then modifyits Position prop
6 Lay Out a UI Using GUIDE6-30To display the & character in a label, use two & characters in the string. The wordsremove, default, and factory
Add Components to the GUIDE Layout Area6-31Note To manage exclusive selection of radio buttons and toggle buttons, put them in abutton group. See “Bu
6 Lay Out a UI Using GUIDE6-32The check box accommodates only a single line of text. If you specify a componentwidth that is too small to accommodate
Add Components to the GUIDE Layout Area6-33• Specify the text to be displayed when the edit text component is created by setting theString property t
xii ContentsSet Colors Interactively . . . . . . . . . . . . . . . . . . . . . . . 10-58Set Font Characteristics Interactively . . . . . . . . . . . .
6 Lay Out a UI Using GUIDE6-34If Max-Min is less than or equal to 1, the edit text component admits only a singleline of input. If you specify a compo
Add Components to the GUIDE Layout Area6-35• Specify the text that appears in the component by setting the component Stringproperty to the desired te
6 Lay Out a UI Using GUIDE6-36• If you want to set the position or size of the component to an exact value, then modifyits Position property. See “Loc
Add Components to the GUIDE Layout Area6-37button to the right of the property name to open the Property Inspector editor.To display the & charac
6 Lay Out a UI Using GUIDE6-38• If you want to set the position and size of the component to exact values, then modifyits Position property. See “Loca
Add Components to the GUIDE Layout Area6-39• Specify the list of items to be displayed by setting the String property to the desiredlist. Use the Pro
6 Lay Out a UI Using GUIDE6-40To display the & character in a label, use two & characters in the string. The wordsremove, default, and factory
Add Components to the GUIDE Layout Area6-41To enable selection of more than one item, you must specify the Max and Minproperties so that their differ
6 Lay Out a UI Using GUIDE6-42• Specify the toggle button label by setting its String property to the desired label, inthis case, Left/Right Tile.To d
Add Components to the GUIDE Layout Area6-43• Create the toggle button with the button selected (depressed) by setting its Valueproperty to the value
xiiiManage Application-Defined Data12Share Data Among Callbacks . . . . . . . . . . . . . . . . . . . . . 12-2Overview of Data Sharing Techniques . .
6 Lay Out a UI Using GUIDE6-44Note To manage exclusive selection of radio buttons and toggle buttons, put them in abutton group. See “Button Group” on
Add Components to the GUIDE Layout Area6-45Property Values DescriptionTitle String Component label.TitlePosition lefttop, centertop,righttop, leftbot
6 Lay Out a UI Using GUIDE6-46• Specify the panel title by setting the Title property to the desired string, in this caseMy Panel.
Add Components to the GUIDE Layout Area6-47To display the & character in the title, use two & characters in the string. The wordsremove, defa
6 Lay Out a UI Using GUIDE6-48Button GroupTo create a button group with title My Button Group as shown in the following figure:• Specify the button gr
Add Components to the GUIDE Layout Area6-49To display the & character in the title, use two & characters in the string. The wordsremove, defa
6 Lay Out a UI Using GUIDE6-50• If you want to set the position or size of the button group to an exact value, thenmodify its Position property. See “
Add Components to the GUIDE Layout Area6-512In the layout area, select the component you are defining.Note See “GUIDE Components” on page 6-13 for a
6 Lay Out a UI Using GUIDE6-52Axes” on page 6-52 and “Axes” on page 10-26 for information about setting theNextPlot property.Create AxesHere is an axe
Add Components to the GUIDE Layout Area6-53• Use the title, xlabel, ylabel, zlabel, and text functions in the UI code file tolabel an axes component.
xiv ContentsView the Example Code . . . . . . . . . . . . . . . . . . . . . . 14-14Set Up and Interact with the uitable . . . . . . . . . . . . . 14-1
6 Lay Out a UI Using GUIDE6-54• If you want to set the position or size of the axes to an exact value, then modify itsPosition property. See “Locate a
Add Components to the GUIDE Layout Area6-55Commonly Used PropertiesThe most commonly used properties of a table component are listed in the table bel
6 Lay Out a UI Using GUIDE6-56Drag the table icon on to the Layout Editor and right click in the table. From the table’scontext menu, select Table Pro
Add Components to the GUIDE Layout Area6-57Use the Table Property EditorWhen you open it this way, the Table Property Editor displays the Column pane
6 Lay Out a UI Using GUIDE6-58definition at a time. These panes contain a vertical group of five buttons for editing andnavigating:Button Purpose Acce
Add Components to the GUIDE Layout Area6-59Select Show names entered below as the column headers and set the ColumnNameby entering Rate, Amount, Avai
6 Lay Out a UI Using GUIDE6-60For the Rate column, select Numeric. For the Amount Column select Custom and in theCustom Format Editor, choose Bank.
Add Components to the GUIDE Layout Area6-61Leave the Available column at the default value. This allows MATLAB to chose basedon the value of the Data
6 Lay Out a UI Using GUIDE6-62Note: For a user to select items from a choice list, the ColumnEditable property of thecolumn that the list occupies mus
Add Components to the GUIDE Layout Area6-63Set Data PropertiesUse the Data property to specify the data in the table. Create the data in the commandw
xvPackaging GUIs as Apps16Apps Overview . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 16-2What Is an App? . . . . . . . .
6 Lay Out a UI Using GUIDE6-64Set Color PropertiesSpecify the BackgroundColor and RowStriping for your table in the Color tab.
Add Components to the GUIDE Layout Area6-65You can change other uitable properties to the table via the Property Inspector.ActiveX ComponentWhen you
6 Lay Out a UI Using GUIDE6-661Select the desired ActiveX control. The right panel shows a preview of the selectedcontrol.2Click Create. The control a
Add Components to the GUIDE Layout Area6-67When you select an ActiveX control, you can open the ActiveX Property Editor by right-clicking and selecti
6 Lay Out a UI Using GUIDE6-68Set the Component's Position PropertySelect one or more components that you want to resize. Then select View > P
Add Components to the GUIDE Layout Area6-692Click the + sign next to Position. The Property Inspector displays the elements ofthe Position property.3
6 Lay Out a UI Using GUIDE6-70Copy, Paste, and Arrange ComponentsThis topic provides basic information about selecting, copying, pasting, and deleting
Copy, Paste, and Arrange Components6-71Copy, Cut, and Clear ComponentsUse standard menu and pop-up menu commands, toolbar icons, keyboard keys, andsh
6 Lay Out a UI Using GUIDE6-72Look for the highlight as described in “Add a Component to a Panel or Button Group”on page 6-20.Front-to-Back Positionin
Copy, Paste, and Arrange Components6-73Note Changing front-to-back positioning of components might change their tabbingbehavior. See “Customize Tabbi
6 Lay Out a UI Using GUIDE6-74Locate and Move ComponentsYou can locate or move components in one of the following ways:In this section...“Use Coordina
Locate and Move Components6-75When you select multiple components, the Position readout displays numbers for x, y,width and height only if the object
6 Lay Out a UI Using GUIDE6-76In some cases, one or more of the selected components may lie outside its parent'sboundary. Such a component is not
Locate and Move Components6-772Click the + sign next to Position. The Property Inspector displays the elements ofthe Position property.
6 Lay Out a UI Using GUIDE6-783If you have selected• Only one component, type the x and y coordinates of the point where you wantthe lower-left corner
Align GUIDE UI Components6-79Align GUIDE UI ComponentsIn this section...“Align Objects Tool” on page 6-79“Property Inspector” on page 6-82“Grid and R
6 Lay Out a UI Using GUIDE6-80The Align Objects tool provides two types of alignment operations:• Align — Align all selected components to a single re
Align GUIDE UI Components6-81All of the align options (vertical top, center, bottom and horizontal left, center, right)place the selected components
6 Lay Out a UI Using GUIDE6-82Property InspectorAbout the Property InspectorIn GUIDE, as in MATLAB generally, you can see and set most components&apos
Align GUIDE UI Components6-83Scroll down to see additional properties. Click any property value or icon to set its value.The Property Inspector provi
Introduction to Creating UIs
6 Lay Out a UI Using GUIDE6-84
Align GUIDE UI Components6-85Use the Property Inspector to Align ComponentsThe Property Inspector enables you to align components by setting their Po
6 Lay Out a UI Using GUIDE6-86ranging from 10 to 200 pixels. You can optionally enable snap-to-grid, which causes anyobject that is moved close to a g
Align GUIDE UI Components6-87
6 Lay Out a UI Using GUIDE6-88Customize Tabbing Behavior in a GUIDE UIA UI's tab order is the order in which components of the UI acquire focus w
Customize Tabbing Behavior in a GUIDE UI6-89To examine and change the tab order of the panel components, click the panelbackground to select it, then
6 Lay Out a UI Using GUIDE6-90The Tab Order Editor displays the panel's components in their current tab order. Tochange the tab order, select a c
Create Menus for GUIDE UIs6-91Create Menus for GUIDE UIsIn this section...“Menus for the Menu Bar” on page 6-91“Context Menus” on page 6-101You can u
6 Lay Out a UI Using GUIDE6-92• “Add Standard Menus to the Menu Bar” on page 6-93• “Create a Menu” on page 6-93• “Add Items to a Menu” on page 6-96• “
Create Menus for GUIDE UIs6-93• The DockControls property is set to 'on' and cannot be turned off untilWindowStyle is no longer set to &apo
6 Lay Out a UI Using GUIDE6-94Note By default, GUIDE selects the Menu Bar tab when you open the Menu Editor.2Click the menu title to display a selecti
Create Menus for GUIDE UIs6-953Fill in the Label and Tag fields for the menu. For example, set Label to File andset Tag to file_menu. Click outside t
6 Lay Out a UI Using GUIDE6-96Add Items to a MenuUse the New Menu Item tool to create menu items that are displayed in the drop-downmenu.1Add an Open
Create Menus for GUIDE UIs6-97You can also• Choose an alphabetic keyboard accelerator for the menu item with the Acceleratorpop-up menu. In combinati
6 Lay Out a UI Using GUIDE6-98• Specify a string for the routine, i.e., the Callback, that performs the actionassociated with the menu item. If you ha
Create Menus for GUIDE UIs6-99Note See “Menu Item” on page 8-22 for information about programming menu items.The following Menu Editor illustration s
6 Lay Out a UI Using GUIDE6-100When you run your program, the menu titles appear in the menu bar.
Create Menus for GUIDE UIs6-101Context MenusA context menu is displayed when a user right-clicks the object for which the menu isdefined. The Menu Ed
6 Lay Out a UI Using GUIDE6-102Create the Parent MenuAll items in a context menu are children of a menu that is not displayed on the figuremenu bar. T
Create Menus for GUIDE UIs6-103Add Items to the Context MenuUse the New Menu Item button to create menu items that are displayed in the contextmenu.1
1About UIs in MATLAB Software• “What Is a UI?” on page 1-2• “How Does a UI Work?” on page 1-4• “Ways to Build MATLAB UIs” on page 1-5
6 Lay Out a UI Using GUIDE6-1042Fill in the Label and Tag fields for the new menu item. For example, set Label toBlue background color and set Tag to
Create Menus for GUIDE UIs6-105You can also modify menu items in these ways:• Display a separator above the menu item by checking Separator above thi
6 Lay Out a UI Using GUIDE6-106callback in the code file using a combination of the Tag field and the UI file name.The callback's name does not d
Create Menus for GUIDE UIs6-107The following figure shows the UIContextMenu property for the axes object with Tagproperty axes1.In the UI code file,
6 Lay Out a UI Using GUIDE6-108Create Toolbars for GUIDE UIsIn this section...“Toolbar and Tools” on page 6-108“Editing Tool Icons” on page 6-116Toolb
Create Toolbars for GUIDE UIs6-109The Toolbar Editor gives you interactive access to all the features of the uitoolbar,uipushtool, and uitoggletool f
6 Lay Out a UI Using GUIDE6-1101Open the UI in GUIDE.2From the View menu, open Property Inspector.3Set the ToolBar property to 'figure' usin
Create Toolbars for GUIDE UIs6-111To add a tool, drag an icon from the Tool Palette into the Toolbar Layout (whichinitially contains the text prompt
6 Lay Out a UI Using GUIDE6-112• Select a tool in the palette and click the Add button.• Double-click a tool in the palette.Dragging allows you to pla
Create Toolbars for GUIDE UIs6-113Predefined and Custom ToolsThe Toolbar Editor provides two types of tools:• Predefined tools, having standard icons
How to Contact MathWorksLatest news:www.mathworks.comSales and services:www.mathworks.com/sales_and_servicesUser community:www.mathworks.com/matlabcen
1 About UIs in MATLAB Software1-2What Is a UI?A user interface (UI) is a graphical display in one or more windows containing controls,called component
6 Lay Out a UI Using GUIDE6-114• Drag a tool to a new position.• Select a tool in the toolbar and click one of the arrow buttons below the right side
Create Toolbars for GUIDE UIs6-115context menu. The Icon Editor opens with the tool’s CData loaded into it. For informationabout editing icons, see “
6 Lay Out a UI Using GUIDE6-116• Click the Close box in the title bar.When you close the Toolbar Editor, the current state of your toolbar is saved wi
Create Toolbars for GUIDE UIs6-117• Icon file name — The icon image file to be loaded for editing• Import button — Opens a file dialog to select an e
6 Lay Out a UI Using GUIDE6-118The Toolbar Editor and Icon Editor are shown together below.
View the GUIDE Object Hierarchy6-119View the GUIDE Object HierarchyThe Object Browser displays a hierarchical list of the objects in the figure, incl
6 Lay Out a UI Using GUIDE6-120Design Cross-Platform UIs in GUIDEIn this section...“Default System Font” on page 6-120“Standard Background Color” on p
Design Cross-Platform UIs in GUIDE6-121Specify a Fixed-Width FontIf you want to use a fixed-width font for a user interface control, set its FontName
6 Lay Out a UI Using GUIDE6-122using the default figure Units of pixels does not produce a UI that looks the same onall platforms.For this reason, GUI
UI Design References6-123UI Design ReferencesMany Web sites such as the following provide guidelines for designing UIs:• AskTog — Essays on good desi
What Is a UI?1-3• A static text component to label the pop-up menu• Three buttons that provide different kinds of plots: surface, mesh, and contourWh
7Save and Run a GUIDE UI• “Save a GUIDE UI” on page 7-2• “Create Programmatic Files from GUIDE Files” on page 7-4• “Rename GUIDE UIs and Files” on pag
7 Save and Run a GUIDE UI7-2Save a GUIDE UIIn this section...“Save a UI” on page 7-2“Create a Backward Compatible GUIDE Fig-File” on page 7-2“Append N
Save a GUIDE UI7-3Append New Callbacks to an Existing GUIDE Code FileIf you save a GUIDE UI to an existing file, GUIDE displays a dialog box that ask
7 Save and Run a GUIDE UI7-4Create Programmatic Files from GUIDE FilesYou can export a GUIDE FIG-file and code file to a single programmatic code file
Rename GUIDE UIs and Files7-5Rename GUIDE UIs and FilesTo rename a UI, rename the FIG-file using Save As from the Layout Editor File menu.GUIDE renam
8Programming a GUIDE UI• “Write Callbacks Using the GUIDE Workflow” on page 8-2• “Initialize UIs Created Using GUIDE” on page 8-7• “Callbacks for Spec
8 Programming a GUIDE UI8-2Write Callbacks Using the GUIDE WorkflowIn this section...“Callbacks for Different User Actions” on page 8-2“GUIDE-Generate
Write Callbacks Using the GUIDE Workflow8-3Callback Property User Action Components That Use This PropertyCreateFcn Callback executes when MATLABcrea
1 About UIs in MATLAB Software1-4How Does a UI Work?Typically, UIs wait for a user to manipulate a control, and then respond to each useraction in tur
8 Programming a GUIDE UI8-4Callback Property User Action Components That Use This PropertyWindowKeyReleaseFcnEnd user releases a key while thepointer
Write Callbacks Using the GUIDE Workflow8-5GUIDE Callback SyntaxAll callbacks must accept at least three input arguments:• hObject — Handle to the UI
8 Programming a GUIDE UI8-6If you decide to change the Tag value after saving the UI, then GUIDE updates thefollowing items (assuming that all compone
Initialize UIs Created Using GUIDE8-7Initialize UIs Created Using GUIDEIn this section...“Opening Function” on page 8-7“Output Function” on page 8-9O
8 Programming a GUIDE UI8-8command line to the opening function. The opening function can take actions withthem (for example, setting property values)
Initialize UIs Created Using GUIDE8-9% with existing figure properties. See the output of set(figure) for% a list of figure properties.if(nargin >
8 Programming a GUIDE UI8-10Function Naming and TemplateGUIDE names the output function by appending _OutputFcn to the name of the UI.This is an examp
Callbacks for Specific Components8-11Callbacks for Specific ComponentsCoding the behavior of a UI component involves specific tasks that are unique t
8 Programming a GUIDE UI8-12If you are creating a UI programmatically, (without GUIDE), then you can adapt theexample code into your code. To adapt an
Callbacks for Specific Components8-13if button_state == get(hObject,'Max') display('down');elseif button_state == get(hObject,&ap
Ways to Build MATLAB UIs1-5Ways to Build MATLAB UIsA MATLAB UI is a figure window to which you add user-operated components. You canselect, size, and
8 Programming a GUIDE UI8-14Check BoxThis code is an example of a check box callback function in GUIDE. Associate thisfunction with the check box Call
Callbacks for Specific Components8-15To enable users to enter multiple lines of text, set the Max and Min properties to numericvalues that satisfy Ma
8 Programming a GUIDE UI8-16% hObject handle to slider1 (see GCBO)% eventdata reserved - to be defined in a future version of MATLAB% handles s
Callbacks for Specific Components8-17 figure uicontrol('Style','Listbox',... 'String',{'Red';'Green&apos
8 Programming a GUIDE UI8-18• Gets the numeric index of the selected item and stores it in the variable,index_selected.• Gets the string value of the
Callbacks for Specific Components8-19Change the Selected ItemWhen the end user selects an item, the pop-up menu’s Value property changes to anumber t
8 Programming a GUIDE UI8-20PanelMake the Panel Respond to Button ClicksYou can create a callback function that executes when the end user right-click
Callbacks for Specific Components8-21set(hObject,'Units','normalized'); newFontSize = 10 * panelHeight / 115; text
8 Programming a GUIDE UI8-22When the end user selects a radio button or toggle button in the button group, thisfunction determines which button the us
Callbacks for Specific Components8-23% --------------------------------------------------------------------function edit_menu_Callback(hObject, event
1 About UIs in MATLAB Software1-6Goal Description of Approachprogrammatically. You can fully defineeach component with a single function call.Create a
8 Programming a GUIDE UI8-24% hObject handle to copy_menu_item (see GCBO)% eventdata reserved - to be defined in a future version of MATLAB% handl
Callbacks for Specific Components8-25if strcmp(get(hObject,'Checked'),'on') set(hObject,'Checked','off');e
8 Programming a GUIDE UI8-26• Sums all the selected values and displays the result in the Command Window.This code is an example of the table callback
Callbacks for Specific Components8-27function axes1_ButtonDownFcn(hObject, eventdata, handles)% hObject handle to axes1 (see GCBO)% eventdata res
8 Programming a GUIDE UI8-28Note: Most MATLAB plotting functions clear the axes and reset a number of axesproperties, including the ButtonDownFcn, bef
Examples of GUIDE UIs8-29Examples of GUIDE UIsThe following are examples that are packaged with MATLAB. The introductory text formost examples provid
9Examples of GUIDE UIs• “Modal Dialog Box in GUIDE” on page 9-2• “UI That Uses Persistent Data” on page 9-7• “UI That Accepts Parameters and Generates
9 Examples of GUIDE UIs9-2Modal Dialog Box in GUIDEIn this section...“About the Example” on page 9-2“Set Up the Close Confirmation Dialog Box” on page
Modal Dialog Box in GUIDE9-34In the Layout Editor, right-click the static text, Do you want to create aquestion dialog?, and select Property Inspecto
2How to Create a UI with GUIDE
9 Examples of GUIDE UIs9-4The code file, closedlg.m, opens in the Editor.On the Editor tab, in the Navigate section, click Go To, and then selectclose
Modal Dialog Box in GUIDE9-53Click Yes or No.• Yes closes both dialog boxes.• No closes just the Confirm Close dialog box.How Close Confirmation Dial
9 Examples of GUIDE UIs9-6delete(handles.figure1)6When the UI with the Close button regains control, it receives the string Yes orNo. If the string is
UI That Uses Persistent Data9-7UI That Uses Persistent DataIn this section...“About the Example” on page 9-7“Calling Syntax” on page 9-8“MAT-file Val
9 Examples of GUIDE UIs9-8copyfile(fullfile(docroot, 'techdoc','creating_guis',... 'examples','addr*.*')),...
UI That Uses Persistent Data9-9 strcmpi(varargin{1},'book') && ... (2 == exist(varargin{2},'file'))) Check_And_Load(var
9 Examples of GUIDE UIs9-10endif exist(file,'file') == 2 data = load(file);end% Validate the MAT-file% The file is valid if the variable
UI That Uses Persistent Data9-11Open and Load MAT-FileThe address book UI contains a File > Open menu option for loading address book MAT-files.Wh
9 Examples of GUIDE UIs9-12• If you create a new entry, you must save the MAT-file using the File > Save menu.The Contact_Name_Callback callback us
UI That Uses Persistent Data9-13switch Answercase 'Yes' Addresses(end+1).Name = Current_Name; % Grow array by 1 Addresses(end).Phone
2 How to Create a UI with GUIDE2-2Create a Simple UI Using GUIDEThis example shows how to use GUIDE to create a simple user interface (UI), such assho
9 Examples of GUIDE UIs9-14case 'Yes' % If no name match was found create a new contact Addresses(handles.Index).Phone = Current_Phone
UI That Uses Persistent Data9-15 % it equal to the index of the % last element in the Addresses array if i < 1 i = length(Addresses
9 Examples of GUIDE UIs9-16the Contact_Name_Callback or the Contact_Phone_Callback updateshandles.Addresses.If you select Save, the save function is c
UI That Uses Persistent Data9-17 guidata(hObject,handles) endendClear UI FieldsThe Create New menu clears the ContactName and ContactPhon
9 Examples of GUIDE UIs9-18When the you resize the window and release the mouse, the SizeChangedFcn callbackexecutes. Unless you have maximized the fi
UI That Uses Persistent Data9-19 % When docked, get out returnend% If resized figure is smaller than original figure, then compensate.% However
9 Examples of GUIDE UIs9-20UI That Accepts Parameters and Generates PlotsIn this section...“About the Example” on page 9-20“UI Design” on page 9-22“Va
UI That Accepts Parameters and Generates Plots9-21To get and view the example code:1Copy the example FIG-file and code file to your current (writeabl
9 Examples of GUIDE UIs9-22If you run the two_axes program and click the Plot button, the UI appears as shownin the preceding figure. The code evaluat
UI That Accepts Parameters and Generates Plots9-23Identify the AxesSince there are two axes in this UI, you must specify which one you want to target
Create a Simple UI Using GUIDE2-32In the GUIDE Quick Start dialog box, select the Blank GUI (Default) template,and then click OK.
9 Examples of GUIDE UIs9-24Validate Input as NumbersWhen you UI displays, you can type parameters into three edit text fields as stringsof text. If yo
UI That Accepts Parameters and Generates Plots9-25a MATLAB expression. Because you can type many things that eval cannot handle,the first task is to
9 Examples of GUIDE UIs9-26The edit text callbacks execute when you enter text in an edit field and press Returnor click elsewhere in the UI. Even if
UI That Accepts Parameters and Generates Plots9-27In this figure, the two plots reflect the last successful set of inputs, f1 = 31.41, f2= 120, and t
9 Examples of GUIDE UIs9-28Plot DataThe final task for the plot_button_Callback is to generate two plots. This involves:• Targeting plots to the appro
UI That Accepts Parameters and Generates Plots9-29Resize and Command-Line OptionsSelect Tools > GUI Options to set these options in your UI:• Resi
9 Examples of GUIDE UIs9-30Synchronized Data Presentations in a GUIDE UIIn this section...“About the Example” on page 9-30“Recreate the UI” on page 9-
Synchronized Data Presentations in a GUIDE UI9-31To get and view the example code:1Copy the example FIG-file and code file to your current (writeable
9 Examples of GUIDE UIs9-322In the GUIDE Layout Editor, click the Editor button .The tablestat.m code file opens in the MATLAB Editor.Recreate the UI
Synchronized Data Presentations in a GUIDE UI9-33Perform the following steps in GUIDE and in the Property Inspector to generate thelayout:1In the Com
2 How to Create a UI with GUIDE2-43Display the names of the UI components in the component palette:aSelect File > Preferences > GUIDE.bSelect Sh
9 Examples of GUIDE UIs9-34bIn the Property Inspector, click the Table Property Editor icon to the right ofthe RowName property to open the Table Pr
Synchronized Data Presentations in a GUIDE UI9-35The Data Statistics table does not use any callbacks.5Use the Axes tool to drag out an axes within
9 Examples of GUIDE UIs9-368Place a second label in the lower axes (axes2), renaming this text object Selectionand setting its Tag property to sellabe
Synchronized Data Presentations in a GUIDE UI9-37Initialize the Data TableAlthough you can use the Opening Function to load data into a table, this e
9 Examples of GUIDE UIs9-38stats{2,col} = min(table(:,2));stats{3,col} = max(table(:,2));stats{4,col} = mean(table(:,2));stats{5,col} = median
Synchronized Data Presentations in a GUIDE UI9-39% hObject handle to plot_type (see GCBO)% eventdata reserved - to be defined in a future version
9 Examples of GUIDE UIs9-40Respond to Data SelectionsThe Data Set table has two columns: Year and Sunspots. The data tables's CellSelection Callb
Synchronized Data Presentations in a GUIDE UI9-41Selection data is generated during mouseDown events (mouse drags in the data table).The uitable pass
9 Examples of GUIDE UIs9-42Caching the list of rows in the selection is necessary because changing plot types canforce selection data to be replotted.
Synchronized Data Presentations in a GUIDE UI9-43Open plot in new window. The static text string (tagged newfig) above the plot panel,Right-click plo
Create a Simple UI Using GUIDE2-5Set the Window Size in GUIDESet the size of the UI window by resizing the grid area in the Layout Editor. Click thel
9 Examples of GUIDE UIs9-44• Make the Tag for the menu plot_axes2.• Create a menu item under it and make its Label Open plot in new windowand assign i
Synchronized Data Presentations in a GUIDE UI9-45% we want to do anything else to themhandles.axes1fig = axes1fig;handles.axes1copy = axes1copy;guida
9 Examples of GUIDE UIs9-46Interactive List Box in a GUIDE UIIn this section...“About the Example” on page 9-46“Implement the List Box” on page 9-47Ab
Interactive List Box in a GUIDE UI9-472From GUIDE Layout Editor, click the Editor button .The lbox2.m code displays in the MATLAB Editor.Implement t
9 Examples of GUIDE UIs9-48% Update handles structureguidata(hObject, handles);if nargin == 3, initial_dir = pwd;elseif nargin > 4 if strcmpi
Interactive List Box in a GUIDE UI9-49• Displays the current folder in the text box by setting its String property to theoutput of the pwd command.Th
9 Examples of GUIDE UIs9-50• Determine whether the selected item is a file or directoryThe load_listbox function uses the dir command to obtain a list
Interactive List Box in a GUIDE UI9-51 try % Use open for other file types. open(filename)
9 Examples of GUIDE UIs9-52Plot Workspace Variables in a GUIDE UIIn this section...“About the Example” on page 9-52“Read Workspace Variables” on page
Plot Workspace Variables in a GUIDE UI9-53To get and view the example code:1Copy the example FIG-file and code file to your current (writeable) folde
Revision HistoryNovember 2000 Online Only New for MATLAB 6.0 (Release 12)June 2001 Online Only Revised for MATLAB 6.1 (Release 12.1)July 2002 Online O
2 How to Create a UI with GUIDE2-6Layout the Simple GUIDE UIAdd, align, and label the components in the UI.1Add the three push buttons to the UI. Sele
9 Examples of GUIDE UIs9-54function update_listbox(handles)vars = evalin('base','who');set(handles.listbox1,'String',var
Plot Workspace Variables in a GUIDE UI9-55• Returns two string variables, if there are two items selected. Otherwiseget_var_names displays an error d
9 Examples of GUIDE UIs9-56The other two plotting buttons work in the same way, resulting in semilogx(x,y) andsemilogy(x,y).
UI for Setting Simulink Model Parameters9-57UI for Setting Simulink Model ParametersIn this section...“About the Example” on page 9-57“How to Use the
9 Examples of GUIDE UIs9-58To get and view the example code:1Copy the example FIG-file and code file to your current (writeable) folder and openthe FI
UI for Setting Simulink Model Parameters9-59You can change either of the gains in one of the two ways:1Move the slider associated with that gain.2Typ
9 Examples of GUIDE UIs9-60• Generate callback function prototypes• GUI allows only one instance to runOpen the Simulink Block DiagramsThis example is
UI for Setting Simulink Model Parameters9-61Slider CallbackThe UI uses two sliders to specify block gains because these components enable theselectio
9 Examples of GUIDE UIs9-62If the value is out of range, the edit text String property is set to the value of theslider (rejecting the number you ente
UI for Setting Simulink Model Parameters9-63• Stores the structure in the handles structure.• Updates the list box String to list the most recent run
Create a Simple UI Using GUIDE2-72Add the remaining components to the UI.• A static text area• A pop-up menu• An axesArrange the components as shown
9 Examples of GUIDE UIs9-64% Store the new ResultsDatahandles.ResultsData = ResultsData;guidata(hObject, handles)Remove Results from List BoxThe Remov
UI for Setting Simulink Model Parameters9-65settings used when the simulation ran. When you click the Plot button, the callbackperforms these tasks:•
9 Examples of GUIDE UIs9-66 '; Ki=', ... num2str(handles.ResultsData(currentVal(ctVal)).KiValue)];end% If necessary, create the p
UI for Setting Simulink Model Parameters9-67• Closes the UI figure.This is the Close button callback:function CloseButton_Callback(hObject, eventdata
9 Examples of GUIDE UIs9-68Animation with Slider Controls in GUIDEIn this section...“About the Example” on page 9-68“Design the 3-D Globe UI” on page
Animation with Slider Controls in GUIDE9-69To get and view the example code:1Copy the example FIG-file and code file to your current (writeable) fold
9 Examples of GUIDE UIs9-70In the GUIDE Layout Editor, the UI looks like this.The UI includes three uipanels that you can barely see in this figure be
Animation with Slider Controls in GUIDE9-71The two sliders allow you to change light direction during animation and functionindependently, but they q
9 Examples of GUIDE UIs9-72UI was saved. For more information on setting tags, see “Identify the Axes” on page 9-23in the previous example.The handles
Animation with Slider Controls in GUIDE9-73object that handles updating the graphics. This example does not explore the technique,but you can find in
2 How to Create a UI with GUIDE2-8Align the ComponentsIf several components have the same parent, you can use the Alignment Tool to alignthem to one a
9 Examples of GUIDE UIs9-74load globe360axis equal offmovie(globeframes)The playback looks like this.Graphics Techniques Used in the 3-D Globe UITo le
Animation with Slider Controls in GUIDE9-75• “Light the Globe and Shift the Light Source” on page 9-77Create the Graphic ObjectsThe axes1_CreateFcn f
9 Examples of GUIDE UIs9-76The surface function plots the surface into the axes. Setting the Parent of the surfaceto hgrotate puts the surface object
Animation with Slider Controls in GUIDE9-77UipanelAxesrotatexformglobesurfacegraticulesurfaceLighttiltxformInsertedobjectsHG Hierarchy for the Exampl
9 Examples of GUIDE UIs9-78handles.light = hlight;handles.tform = hgrotate;handles.hmesh = hmesh;handles.azimuth = 0.;handles.cmap = cmap;guidata(gcf,
Automatically Refresh Plot in a GUIDE UI9-79Automatically Refresh Plot in a GUIDE UIIn this section...“About the Example” on page 9-79“The Timer Impl
9 Examples of GUIDE UIs9-80To get and view the example code:1Copy the example FIG-file and code file to your current (writeable) folder and openthe FI
Automatically Refresh Plot in a GUIDE UI9-81For details about timer properties, methods, and events, see “Use a MATLAB TimerObject” and the timer ref
9 Examples of GUIDE UIs9-82ex_guide_timergui_OpeningFcnex_guide_timergui_OpeningFcn creates the timer using the following code:handles.timer = timer(.
Automatically Refresh Plot in a GUIDE UI9-83period = get(handles.periodsldr,'Value');% Timers need the precision of periods to be greater t
Create a Simple UI Using GUIDE2-94Click OK.
9 Examples of GUIDE UIs9-84end% Destroy timerdelete(handles.timer)% Destroy figuredelete(hObject);
Create UIs Programmatically• “Lay Out a UI Programmatically”• “Create Menus for Programmatic UIs”• “Create Toolbars for Programmatic UIs”• “Create a S
10Lay Out a Programmatic UI• “Structure of Programmatic UI Code Files” on page 10-2• “Create Figures for Programmatic UIs” on page 10-4• “Programmatic
10 Lay Out a Programmatic UI10-2Structure of Programmatic UI Code FilesIn this section...“File Organization” on page 10-2“File Template” on page 10-2“
Structure of Programmatic UI Code Files10-3% Initialization tasks% Construct the components% Initialization tasks% Callbacks for MYUI% Utility f
10 Lay Out a Programmatic UI10-4Create Figures for Programmatic UIsIn MATLAB software, a UI is a figure. Before you add components to it, create thefi
Create Figures for Programmatic UIs10-5Property Values Description• none — do not display thefigure toolbar.• auto — display the figuretoolbar, but r
10 Lay Out a Programmatic UI10-6Programmatic ComponentsThe following table describes the available components and the function used to createeach prog
Programmatic Components10-7Component Function Descriptionpanels. The position of each componentwithin a panel is interpreted relative to thepanel. If
2 How to Create a UI with GUIDE2-10Label the Push ButtonsEach of the three push buttons specifies a plot type: surf, mesh, and contour. This topicshow
10 Lay Out a Programmatic UI10-8Component Function Description“Tables” on page10-21uitable Tables contain rows of numbers, textstrings, and choices gr
Add Components to a Programmatic UI10-9Add Components to a Programmatic UIIn this section...“User Interface Controls” on page 10-9“Tables” on page 10
10 Lay Out a Programmatic UI10-10The first uicontrol argument, f, specifies the parent container. In this case, the parentis a figure, but you can als
Add Components to a Programmatic UI10-11 'String','Indent nested functions.',... 'Value',
10 Lay Out a Programmatic UI10-12The first uicontrol argument, f, specifies the parent container. In this case, the parentis a figure, but you can als
Add Components to a Programmatic UI10-13 'Value',1,'Position',[30 20 130 20]);The first uicontrol argument, f, spe
10 Lay Out a Programmatic UI10-14The first uicontrol argument, f, specifies the parent container. In this case, the parentis a figure, but you can als
Add Components to a Programmatic UI10-15bar, you can uses this behavior to indicate how much of the document is currently visibleby changing the valu
10 Lay Out a Programmatic UI10-16The first uicontrol argument, f, specifies the parent container. In this case, the parentis a figure, but you can als
Add Components to a Programmatic UI10-17'String','Enter your name here', specifies the default text to display.The next pair, &ap
Create a Simple UI Using GUIDE2-112In the layout area, click the top push button.3In the Property Inspector, select the String property, and then rep
10 Lay Out a Programmatic UI10-18Pop-Up MenuThis code creates a pop-up menu:f = figure;pm = uicontrol(f,'Style','popupmenu',...
Add Components to a Programmatic UI10-19The first uicontrol argument, f, specifies the parent container. In this case, the parentis a figure, but you
10 Lay Out a Programmatic UI10-20The first uicontrol argument, f, specifies the parent container. In this case, the parentis a figure, but you can als
Add Components to a Programmatic UI10-21If you want no initial selection, set these property values:• Set the Max and Min properties such that Max -
10 Lay Out a Programmatic UI10-22You can change several other characteristics of the table by setting certain properties:• To control the user’s abili
Add Components to a Programmatic UI10-23The first argument passed to uipanel, f, specifies the parent container. In this case,the parent is a figure,
10 Lay Out a Programmatic UI10-24b1 = uicontrol(p,'Style','pushbutton','String','Button 1',...
Add Components to a Programmatic UI10-25The first argument passed to uibuttongroup, f, specifies the parent container. In thiscase, the parent is a f
10 Lay Out a Programmatic UI10-26rb1 = uicontrol(bg,'Style','radiobutton','String','Red',... &a
Add Components to a Programmatic UI10-27f = figure;ax = axes('Parent',f,'Position',[.15 .15 .7 .7]);The first two arguments passe
2 How to Create a UI with GUIDE2-125Click each of the remaining push buttons in turn and repeat steps 3 and 4. Label themiddle push button Mesh, and t
10 Lay Out a Programmatic UI10-28The default value of the NextPlot axes property, 'replace' allows the graphingfunctions to reset many prope
Add Components to a Programmatic UI10-29uisetfont returns the selections as a structure array:myfont = FontName: 'Century Schoolbook'
10 Lay Out a Programmatic UI10-30Related Examples• “Callbacks for Specific Components”
Lay Out a UI Programmatically10-31Lay Out a UI ProgrammaticallyYou can adjust the size and location of components, and manage front-to-back orderof g
10 Lay Out a Programmatic UI10-32You can query or change the outer bounds of the figure by using the OuterPositionproperty. Like the Position property
Lay Out a UI Programmatically10-33Explicitly changing the Position or OuterPosition causes the other property to change.For example, this is the curr
10 Lay Out a Programmatic UI10-34 258 258 474 248Other UI components, such as uicontrols, uitables, and uipanels have a Positionproperty, whic
Lay Out a UI Programmatically10-35 % Make figure visible after adding components hs.fig.Visible = 'on'; function hs = addcomponent
10 Lay Out a Programmatic UI10-36Managing the Layout in Resizable UIsTo create a resizable UI and manage the layout when the user resizes the window,
Lay Out a UI Programmatically10-37If your UI has another container, such as a uipanel or uibuttongroup, you can managethe layout of the container’s c
Create a Simple UI Using GUIDE2-133Replace the existing text with the names of the three data sets: peaks, membrane,and sinc. Press Enter to move to
10 Lay Out a Programmatic UI10-38 'Units','pixels',... 'Tag','ax'); end
Lay Out a UI Programmatically10-39• The value of the axes width, axwidth, allows 50 pixels of space between the right sideof the axes and the right e
10 Lay Out a Programmatic UI10-40Adjust Programmatic UI Layouts InteractivelyIn this section...“Set Positions of Components Interactively” on page 10-
Adjust Programmatic UI Layouts Interactively10-41Note: The following sections describe some techniques for interactively refining theappearance of UI
10 Lay Out a Programmatic UI10-42Tip Instead of using a separate set command, after you decide upon a position for theobject, you can modify the state
Adjust Programmatic UI Layouts Interactively10-43Use Plot Edit Mode to Change PropertiesAfter you select an object in plot edit mode, you can open th
10 Lay Out a Programmatic UI10-44Scroll in the help window to view descriptions of other properties.
Adjust Programmatic UI Layouts Interactively10-45The following Inspector image illustrates using the Inspector to change the Max propertyof a slider
10 Lay Out a Programmatic UI10-46Most of the properties that the Property Editor can set are cosmetic. To modify valuesfor other properties, click Mor
Adjust Programmatic UI Layouts Interactively10-47You can obtain the new property value using dot notation and the property name. Forexample, this com
2 How to Create a UI with GUIDE2-143Click OK.The phrase Select Data appears in the static text component above the pop-upmenu.Save the UI LayoutWhen y
10 Lay Out a Programmatic UI10-48The setpos function uses figure units to set the component Position property. First,setpos gets and saves the Units p
Adjust Programmatic UI Layouts Interactively10-493Release the mouse button. The control moves.
10 Lay Out a Programmatic UI10-504The button Position is set, returned and placed on the system clipboard:rect = 37 362 127 27Add a Position p
Adjust Programmatic UI Layouts Interactively10-51btn1 = uicontrol('Style','pushbutton','String','Push Me',...
10 Lay Out a Programmatic UI10-52A syntax for the align function isalign(HandleList,'HorizontalAlignment','VerticalAlignment')The
Adjust Programmatic UI Layouts Interactively10-53uicontrol and do not specify a Position, their location is always [20 20 60 20] (inpixels). That is,
10 Lay Out a Programmatic UI10-54Align Components Vertically While Distributing Them HorizontallyThe following statement moves the push buttons to the
Adjust Programmatic UI Layouts Interactively10-55Use Align Distribute ToolsIf your figure has a standard menu bar, you can perform align and distribu
10 Lay Out a Programmatic UI10-56The following steps illustrate how to use the Align Distribute tool to arrange componentsin a UI. The tool provides t
Adjust Programmatic UI Layouts Interactively10-57Note: One thing to remember when aligning components is that the align functionuses units of points
Create a Simple UI Using GUIDE2-15Click Yes.3GUIDE opens a Save As dialog box in your current folder and prompts you for aFIG-file name.4Browse to an
10 Lay Out a Programmatic UI10-58Set Colors InteractivelySpecifying colors for Color, ForegroundColor, BackgroundColor, FontColor, andplotting object
Adjust Programmatic UI Layouts Interactively10-59When you execute the statement, first getrect executes to let you set a position usingrbbox. When yo
10 Lay Out a Programmatic UI10-60calling inputdlg, which is a dialog that allows you to enter text strings. Here is anexample that creates static text
Adjust Programmatic UI Layouts Interactively10-61When you specify a font, style, and size and click OK, the text appears in the figurewindow.
10 Lay Out a Programmatic UI10-62Customize Tabbing Behavior in a Programmatic UIIn this section...“How Tabbing Works” on page 10-62“Default Tab Order”
Customize Tabbing Behavior in a Programmatic UI10-63 'Position',[290 200 130 20]);sth = uicontrol(fh,'Style','text
10 Lay Out a Programmatic UI10-64 3x1 UIControl array: UIControl (Surf) UIControl (Mesh) UIControl (Contour) The default tab order is the
Customize Tabbing Behavior in a Programmatic UI10-65The tab order of the three buttons is now Contour, then Surf, then Mesh.This command shows the ne
10 Lay Out a Programmatic UI10-66Create Menus for Programmatic UIsIn this section...“Add Menu Bar Menus” on page 10-66“Add Context Menus to a Programm
Create Menus for Programmatic UIs10-67If you use the standard menu bar menus, any menus you create are added to it. If youchoose not to display the s
2 How to Create a UI with GUIDE2-16To run a program created with GUIDE without opening GUIDE, execute its code file bytyping its name. simple_guiYou c
10 Lay Out a Programmatic UI10-68Property Values DescriptionAccelerator Alphabetic character Keyboard equivalent. Availablefor menu items that do not
Create Menus for Programmatic UIs10-69Figure windows with a standard menu bar also have a Desktop menu from which theuser can dock and undock them.To
10 Lay Out a Programmatic UI10-70Menu Bar MenuThe following statements create a menu bar menu with two menu items.mh = uimenu(fh,'Label',&ap
Create Menus for Programmatic UIs10-71This command adds a separator line preceding the second menu item.eh2.Separator = 'on';
10 Lay Out a Programmatic UI10-72The following statements add two menu subitems to Item 1, assign each subitem akeyboard accelerator, and disable the
Create Menus for Programmatic UIs10-73Add Context Menus to a Programmatic UIContext menus appear when the user right-clicks on a figure or UI compone
10 Lay Out a Programmatic UI10-74Property Values DescriptionVisible off, on. Default isoff• Indicates whether the context menu iscurrently displayed.
Create Menus for Programmatic UIs10-75mh1 = uimenu(cmenu,'Label','Item 1');mh2 = uimenu(cmenu,'Label','Item 2&apos
10 Lay Out a Programmatic UI10-76This code associates the context menu with the figure and with the axes by setting theUIContextMenu property of the f
Create Menus for Programmatic UIs10-77Force Display of the Context MenuIf you set the context menu Visible property on, the context menu is displayed
Create a Simple UI Using GUIDE2-17respond because the functions contain no statements that perform actions yet. This topicshows you how to add code t
10 Lay Out a Programmatic UI10-78If you set the context menu Visible property to off, or if the user clicks outside thecontext menu, the context menu
Create Toolbars for Programmatic UIs10-79Create Toolbars for Programmatic UIsIn this section...“Use the uitoolbar Function” on page 10-79“Commonly Us
10 Lay Out a Programmatic UI10-80Property Values Descriptiondisplayed on either a push button ortoggle button.HandleVisibility on, off. Default is on.
Create Toolbars for Programmatic UIs10-81% Add a toggle tool to the toolbarimg2 = rand(16,16,3);tth = uitoggletool(tbh,'CData',img2,'S
10 Lay Out a Programmatic UI10-82TooltipString specifies the tooltips for the push tool and the toggle tool as My pushtool and Your toggle tool, respe
Create Toolbars for Programmatic UIs10-83If necessary, you can use the findall function to determine the handles of the tools on aparticular toolbar.
10 Lay Out a Programmatic UI10-84Display the Standard ToolbarUse the figure Toolbar property to display or hide the standard toolbar. Set Toolbar to&a
Fonts and Colors for Cross-Platform Compatibility10-85Fonts and Colors for Cross-Platform CompatibilityIn this section...“Default System Font” on pag
10 Lay Out a Programmatic UI10-86Standard Background ColorMATLAB uses the standard system background color of the system on which the UIis running as
11Code a Programmatic UI• “Initialize a Programmatic UI” on page 11-2• “Write Callbacks Using the Programmatic Workflow” on page 11-5
2 How to Create a UI with GUIDE2-18handles.sinc = sinc;% Set the current data value.handles.current_data = handles.peaks;surf(handles.current_data)The
11 Code a Programmatic UI11-2Initialize a Programmatic UIPrograms that present a UI might perform these tasks when you launch them:• Define default va
Initialize a Programmatic UI11-3The fullfile function builds a full filename from parts.The following statements start the Icon Editor application. T
11 Code a Programmatic UI11-41A call to uiwait blocks execution until uiresume is called or the current figure isdeleted.2While execution is blocked,
Write Callbacks Using the Programmatic Workflow11-5Write Callbacks Using the Programmatic WorkflowIn this section...“Callbacks for Different User Act
11 Code a Programmatic UI11-6Callback Property User Action Components That Use This PropertyCreateFcn Callback executes when MATLABcreates the object,
Write Callbacks Using the Programmatic Workflow11-7Callback Property User Action Components That Use This PropertyWindowKeyReleaseFcnEnd user release
11 Code a Programmatic UI11-8 disp(['Slider moved to ' newval]);endThis callback function displays the value of the slider when the end us
Write Callbacks Using the Programmatic Workflow11-9Like callbacks specified as function handles, MATLAB checks callbacks specified as cellarrays for
11 Code a Programmatic UI11-10it as an empty array. The following table lists the callbacks and components that usecallbackdata.Callback Property Name
12Manage Application-Defined Data
Create a Simple UI Using GUIDE2-191Display the pop-up menu callback in the MATLAB Editor. In the GUIDE LayoutEditor, right-click the pop-up menu comp
12 Manage Application-Defined Data12-2Share Data Among CallbacksIn this section...“Overview of Data Sharing Techniques” on page 12-2“Store Data in Use
Share Data Among Callbacks12-3Method Description Requirements and Trade-OffsUIs)” on page12-5• Can share multiple variables.“Store DataUsing theguida
12 Manage Application-Defined Data12-4endfunction button_callback(hObject,eventdata) h = findobj('Tag','slider1'); data = h.UserDa
Share Data Among Callbacks12-5slider = uicontrol('Parent', hfig,'Style','slider',... 'Units','no
12 Manage Application-Defined Data12-6the slider position. To see how it works, copy and paste this code into an editor and runit.function my_slider()
Share Data Among Callbacks12-7search for a specific UI component to access your data. Call guidata with two inputarguments to store data:guidata(obje
12 Manage Application-Defined Data12-8 'Position',[0.4 0.3 0.2 0.1],... 'String','Display Values',...
Share Data Among Callbacks12-92Copy the example code.copyfile(fullfile(docroot, 'techdoc','creating_guis',... 'examples&apo
12 Manage Application-Defined Data12-10copyfile(fullfile(docroot, 'techdoc','creating_guis',... 'examples','guide*
13Manage Callback Execution
2 How to Create a UI with GUIDE2-20This code first retrieves two pop-up menu properties:• String — a cell array that contains the menu contents• Value
13 Manage Callback Execution13-2Interrupt Callback ExecutionIn this section...“How to Control Interruption” on page 13-2“Callback Behavior When Interr
Interrupt Callback Execution13-3• If the running callback contains one of these commands, then MATLAB stops theexecution of the running callback and
13 Manage Callback Execution13-4Clicking specific pairs of buttons demonstrates the effect of different property valuecombinations :
Interrupt Callback Execution13-5• Callback interruption — Click Wait (interruptible) immediately followed by eitherbutton in the second window: Surf
13 Manage Callback Execution13-6Here is the command that creates the Mesh Plot (cancel) push button. Notice that theBusyAction property is set to &apo
14Examples of UIs CreatedProgrammatically• “Axes, Menus, and Toolbars in Programmatic UIs” on page 14-2• “Synchronized Data Presentations in a Program
14 Examples of UIs Created Programmatically14-2Axes, Menus, and Toolbars in Programmatic UIsIn this section...“About the Example” on page 14-2“View th
Axes, Menus, and Toolbars in Programmatic UIs14-3You can select other plots in the pop-up menu. Clicking the Update button displays thecurrently sele
14 Examples of UIs Created Programmatically14-4mPlotTypes is a 5-by-2 cell array that specifies graphing functions and data. The firstcolumn contains
Axes, Menus, and Toolbars in Programmatic UIs14-5hPlotAxes = axes(... % Axes for plotting the selected plot 'Parent', hM
Create a Simple UI Using GUIDE2-21In the Editor, the cursor moves to the Surf push button callback in the UI code file,which contains this code:% ---
14 Examples of UIs Created Programmatically14-6• For a push button, the String property defines the label on the button. Here it isdefined as the stri
Axes, Menus, and Toolbars in Programmatic UIs14-7• For each of the menu items, the Callback property specifies the callback thatservices that item. T
14 Examples of UIs Created Programmatically14-8end• The localUpdatePlot function creates a plot in the axes. The localUpdatePlotfunction gets the pop-
Axes, Menus, and Toolbars in Programmatic UIs14-9endThe hOpenMenuitemCallback function first calls the uigetfile function to open thestandard dialog
14 Examples of UIs Created Programmatically14-10The hPrintMenuitemCallback function calls the printdlg function. This functionopens the standard syste
Axes, Menus, and Toolbars in Programmatic UIs14-11 delete(hMainFigure);endThe hCloseMenuitemCallback function calls the questdlg function to creat
14 Examples of UIs Created Programmatically14-12Synchronized Data Presentations in a Programmatic UIIn this section...“Techniques Illustrated in the E
Synchronized Data Presentations in a Programmatic UI14-13The program displays and removes line plots when the user selects and clears the threecheck
14 Examples of UIs Created Programmatically14-14View the Example CodeTo obtain copies of the program files for this example, follow these steps:1Set y
Synchronized Data Presentations in a Programmatic UI14-15% Create a uitable on the left side of the figurehtable = uitable('Units', 'n
2 How to Create a UI with GUIDE2-22• Add this code to the Mesh push button callback, pushbutton2_Callback: % Display mesh plot of the currently selec
14 Examples of UIs Created Programmatically14-16in the workspace after being copied into the table). However, the function hides themarkers immediatel
Synchronized Data Presentations in a Programmatic UI14-17 xvals = sel(:,1); xvals(sel(:,2) ~= col) = []; yvals = tab
14 Examples of UIs Created Programmatically14-18Setting the z-values ensures that the markers plot on top of the lines.5Assigns x-, y-, and z-values t
Synchronized Data Presentations in a Programmatic UI14-19 % Obtain the data for that column ydata = htable.Data; haxes.NextPlot
14 Examples of UIs Created Programmatically14-20Lists of Items in a Programmatic UIIn this section...“About the Example” on page 14-20“View the Exampl
Lists of Items in a Programmatic UI14-21View the Example CodeThe example includes one code file, two MAT-files and a text file:• listmaster.m — The U
14 Examples of UIs Created Programmatically14-22List Master looks for the listmaster_icons.mat MAT-file when creating a new UI(from File > New men
Lists of Items in a Programmatic UI14-23Because the positions of all controls are specified in normalized Units, the UI isresizable. Only the button
14 Examples of UIs Created Programmatically14-24Import Data into List MasterYou can import data into the UI at any time. If the UI already contains da
Lists of Items in a Programmatic UI14-25that to paste new items into a list, you must add them one at a time via the edit text box.It also means you
Create a Simple UI Using GUIDE2-233Try other combinations before closing the window.
14 Examples of UIs Created Programmatically14-26Program List MasterThe List Master UI code file contains 22 functions, organized into five groups, whi
Lists of Items in a Programmatic UI14-27Here is the code that calculates the initial position of the UI window:su = get(groot,'Units');set(
14 Examples of UIs Created Programmatically14-28lmnew then calls the enable_updown function. The enable_updown function sets theEnable property of the
Lists of Items in a Programmatic UI14-29List Master List CallbacksThe six callbacks not associated with menu items are listed and described in this t
14 Examples of UIs Created Programmatically14-30Likewise, specifying the figure handle to findobj assures that only one list box handleis returned, re
Lists of Items in a Programmatic UI14-31setappdata(fh,'Dirty',yes_no);% Also disable or enable the File->Save item according to yes_nosa
14 Examples of UIs Created Programmatically14-32UI for a Program That Accepts ArgumentsIn this section...“About the Example” on page 14-32“Copy and Vi
UI for a Program That Accepts Arguments14-331Clicking a color cell toggle button makes the program perform these actions:• Display the selected color
14 Examples of UIs Created Programmatically14-34mGetColorFcn = colorPalette('Parent',hPaletteContainer)The colorPalette function accepts pro
UI for a Program That Accepts Arguments14-35Function DescriptionhPalettePanelSelectionChangedExecutes when the user clicks on a new color. This is th
2 How to Create a UI with GUIDE2-24Files Generated by GUIDEIn this section...“Code Files and FIG-Files” on page 2-24“UI Code File Structure” on page 2
14 Examples of UIs Created Programmatically14-364Figure window and component creation.5UI initialization.6Callback definitions. These callbacks, which
UI for a Program That Accepts Arguments14-37• The third column is the local variable that holds the value of the property.colorPalette then initializ
15Apps• “Find Apps” on page 15-2• “View App File List” on page 15-3• “Run, Uninstall, Reinstall, and Install Apps” on page 15-5• “Install Apps in a Sh
15 Apps15-2Find AppsApps are included in some MATLAB products (such as Curve Fitting Toolbox™, SignalProcessing Toolbox™, and Control System Toolbox™)
View App File List15-3View App File ListIn this section...“Before Installing” on page 15-3“After Installing” on page 15-3Before InstallingBefore inst
15 Apps15-4.mlappinstall file. For information on locating the.mlappinstall file, see“Change Apps Installation Folder” on page 15-8.
Run, Uninstall, Reinstall, and Install Apps15-5Run, Uninstall, Reinstall, and Install AppsIn this section...“Run App” on page 15-5“Install or Reinsta
15 Apps15-6Uninstall AppTo uninstall an app that appears in the apps gallery under My Apps:1On the desktop toolstrip, click the Apps tab.2On the far r
Install Apps in a Shared Network Location15-7Install Apps in a Shared Network LocationIf you are responsible for administering MATLAB software for yo
Files Generated by GUIDE2-25mygui.m, then the name of the main function is mygui. Each callback in the file is a localfunction of that main function.
15 Apps15-8Change Apps Installation FolderBy default, MATLAB installs apps from .mlappinstall files in the userpath \Apps\appname folder. The userpath
16Packaging GUIs as Apps• “Apps Overview” on page 16-2• “Package Apps” on page 16-5• “Modify Apps” on page 16-7• “Share Apps” on page 16-8• “MATLAB Ap
16 Packaging GUIs as Apps16-2Apps OverviewWhat Is an App?A MATLAB app is a self-contained MATLAB program with a user interface thatautomates a task or
Apps Overview16-3• MATLAB ProductsMany MATLAB products, such as Curve Fitting Toolbox, Signal Processing Toolbox,and Control System Toolbox include a
16 Packaging GUIs as Apps16-4In addition when others install your app:• It is a one-click installation.• Users do not need to manage the MATLAB search
Package Apps16-5Package AppsPackage apps you create into an app package for sharing with others. When you createan app package, MATLAB creates a sing
16 Packaging GUIs as Apps16-6You can include external interfaces, such as MEX-files, ActiveX, or Java® in the.mlappinstall file, although doing so can
Modify Apps16-7Modify AppsWhen you update the files included in a .mlappinstall file, you recreate and overwritethe original app. You cannot maintain
16 Packaging GUIs as Apps16-8Share AppsTo share your app with others, give them the .mlappinstall file. All files youadded when you packaged the app a
MATLAB App Installer File — mlappinstall16-9MATLAB App Installer File — mlappinstallA MATLAB app installer file, .mlappinstall, is an archive file fo
vContentsIntroduction to Creating UIsAbout UIs in MATLAB Software1What Is a UI? . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
2 How to Create a UI with GUIDE2-26• Double-click a component to show its properties in the Property Inspector. In theProperty Inspector, click the pe
16 Packaging GUIs as Apps16-10Dependency AnalysisWhen you create an app package, MATLAB analyzes your main file and attempts toinclude all the MATLAB
Files Generated by GUIDE2-27callback code manually. For details, see “Renaming and Removing GUIDE-GeneratedCallbacks” on page 8-5.
3A Simple Programmatic UI
3 A Simple Programmatic UI3-2Create a Simple UI ProgrammaticallyThis example shows how to create a simple UI programmatically, such as the one shownhe
Create a Simple UI Programmatically3-3To run the code, go to the Run section in the Editor tab. Then click Run .Create a Code File for the Simple P
3 A Simple Programmatic UI3-4• The Position property is a four-element vector that specifies the location of the UIon the screen and its size: [distan
Create a Simple UI Programmatically3-5The pop-up menu component String property uses a cell array to specify the threeitems in the pop-up menu: Peaks
3 A Simple Programmatic UI3-6 hpopup = uicontrol('Style','popupmenu',... 'String',{'Peaks','M
Create a Simple UI Programmatically3-7Value property to the index of the selected string. The pop-up menu callback reads thepop-up menu Value propert
vi ContentsA Simple Programmatic UI3Create a Simple UI Programmatically . . . . . . . . . . . . . . 3-2Create a Code File for the Simple Programmatic
3 A Simple Programmatic UI3-8endfunction contourbutton_Callback(source,eventdata) % Display contour plot of the currently selected data. contour(c
Create a Simple UI Programmatically3-9Initialize the Simple Programmatic UIInitialize the UI, so it is ready for the user when the code makes the UI
3 A Simple Programmatic UI3-10Verify Code and Run the ProgramMake sure your code appears as it should, and then run it.1Verify that your code file loo
Create a Simple UI Programmatically3-11peaks_data = peaks(35);membrane_data = membrane;[x,y] = meshgrid(-8:.5:8);r = sqrt(x.^2+y.^2) + eps;sinc_data
3 A Simple Programmatic UI3-12 end function meshbutton_Callback(source,eventdata) % Display mesh plot of the currently selected data. mesh(c
Create a Simple UI Programmatically3-13help simple_gui2 SIMPLE_GUI2 Select a data set from the pop-up menu, then click one of the plot-type push bu
Create UIs with GUIDE
4What Is GUIDE?• “GUIDE: Getting Started” on page 4-2• “GUIDE Tools Summary” on page 4-3
viiGenerate FIG-File and MATLAB File . . . . . . . . . . . . . 5-10Generate FIG-File Only . . . . . . . . . . . . . . . . . . . . . . . 5-12Lay Out a
4 What Is GUIDE?4-2GUIDE: Getting StartedIn this section...“UI Layout” on page 4-2“UI Programming” on page 4-2UI LayoutGUIDE is a development environm
GUIDE Tools Summary4-3GUIDE Tools SummaryThe GUIDE tools are available from the Layout Editor shown in the figure below. Thetools are called out in t
4 What Is GUIDE?4-4Use This Tool... To...Components to the GUIDE Layout Area” on page 6-17 for moreinformation.Figure ResizeTabSet the size at which t
5GUIDE Preferences and Options• “GUIDE Preferences” on page 5-2• “GUIDE Options” on page 5-8
5 GUIDE Preferences and Options5-2GUIDE PreferencesIn this section...“Set Preferences” on page 5-2“Confirmation Preferences” on page 5-2“Backward Comp
GUIDE Preferences5-3Prompt to Save on ActivateWhen you activate a UI from the Layout Editor by clicking the Run button , a dialogbox informs you of
5 GUIDE Preferences and Options5-4Prompt to Save on ExportFrom the Layout Editor, when you select File > Export, a dialog box informs you of theimp
GUIDE Preferences5-5The following topics describe the preferences in this dialog:• “Show Names in Component Palette” on page 5-5• “Show File Extensio
5 GUIDE Preferences and Options5-6Show File Extension in Window TitleDisplays the FIG-file file name with its file extension, .fig, in the Layout Edit
GUIDE Preferences5-7% --- Executes during object deletion, before destroying properties.function figure1_DeleteFcn(hObject, eventdata, handles)% hObj
viii ContentsAlign GUIDE UI Components . . . . . . . . . . . . . . . . . . . . . 6-79Align Objects Tool . . . . . . . . . . . . . . . . . . . . . . .
5 GUIDE Preferences and Options5-8GUIDE OptionsIn this section...“The GUI Options Dialog Box” on page 5-8“Resize Behavior” on page 5-9“Command-Line Ac
GUIDE Options5-9Resize BehaviorYou can control whether users can resize the window and how MATLAB handlesresizing. GUIDE provides three options:• Non
5 GUIDE Preferences and Options5-10h = gcfFor a UI created in GUIDE, set the Command-line accessibility option to preventusers from inadvertently chan
GUIDE Options5-11GUIDE also adds a callback whenever you edit a callback routine from the LayoutEditor's right-click context menu and when you a
5 GUIDE Preferences and Options5-12To ensure that the figure background matches the color of the components, select Usesystem color scheme for backgro
GUIDE Options5-13Callbacks for UIs without CodeEven when there is no code file associated with a UI FIG-file, you can still providecallbacks for UI c
6Lay Out a UI Using GUIDE• “GUIDE Templates” on page 6-2• “Set the UI Window Size in GUIDE” on page 6-11• “GUIDE Components” on page 6-13• “Add Compon
6 Lay Out a UI Using GUIDE6-2GUIDE TemplatesIn this section...“Access the Templates” on page 6-2“Template Descriptions” on page 6-3Access the Template
GUIDE Templates6-3To use a template:1Select a template in the left pane. A preview displays in the right pane.2Optionally, name your UI now by select
ixProgramming a GUIDE UI8Write Callbacks Using the GUIDE Workflow . . . . . . . . . 8-2Callbacks for Different User Actions . . . . . . . . . . . . .
6 Lay Out a UI Using GUIDE6-4Select this template when the other templates are not suitable for the UI you want tocreate.GUI with UicontrolsThe follow
GUIDE Templates6-5When you click the Run button , the UI appears as shown in the following figure.
6 Lay Out a UI Using GUIDE6-6When you enter values for the density and volume of an object, and click the Calculatebutton, the program calculates the
GUIDE Templates6-7When you click the Run button on the toolbar, the UI displays a plot of five lines, eachof which is generated from random numbers
6 Lay Out a UI Using GUIDE6-8You can select other plots in the pop-up menu. Clicking the Update button displays thecurrently selected plot on the axes
GUIDE Templates6-9When you click the Run button, the following dialog displays.
6 Lay Out a UI Using GUIDE6-10The dialog returns the text string, Yes or No, depending on which button you click.Select this template if you want your
Set the UI Window Size in GUIDE6-11Set the UI Window Size in GUIDESet the size of the UI window by resizing the grid area in the Layout Editor. Click
6 Lay Out a UI Using GUIDE6-12Set the Window Position or Size to an Exact Value1In the Layout Editor, open the Property Inspector for the figure by cl
GUIDE Components6-13GUIDE ComponentsThe component palette at the left side of the Layout Editor contains the components thatyou can add to your UI. Y
Commentaires sur ces manuels