MATLAB has a number of graphical user interface (GUI) tools and functions that can be employed while building GUI models, either by using the GUI tools or by writing scripts. In this chapter, we cover how to build GUI models with the GUI development environment (GUIDE) and how to write scripts to generate popup and dialog boxes.
GUIDE
MATLAB GUI components are graphical controls (push buttons, edit boxes, lists, sliders, and popup menus), static elements (frames, text strings), menus, and axes. Graphical control elements and static elements can be created by using the uicontrol function. Menus can be generated by using the uimenu and uicontextmenu functions. The axes function is used to display graphical data.
The figure function is used to create figures that accommodate various combinations of components.
Callbacks or callback functions are used to perform actions (simulations and displays) with respect to user entries, such as clicks with a cursor (mouse or touch screen) or entries from the keyboard.
All of these components and figures and their properties and behaviors can be created by writing scripts, functions, and callback functions using MATLAB’s built-in functionality tools. However, this approach is rather cumbersome and long, and it requires a considerable amount of code and programming. An alternative and rather straightforward approach to designing a GUI model is MATLAB’s user-friendly GUI development environment (GUIDE) tool.
GUIDE contains templates, including GUI with UI controls, GUI with axes and menus, and the modal question dialog. By using this tool, you can rather easily create a GUI model layout with all the necessary components, such as push buttons, menus, static elements, text, and so forth, and adjust their properties (size, color, type, etc.) and location with respect to the GUI model design. This can be done by using the mouse and keyboard, without any programming. Note that MATLAB (starting from MATLAB R2016a) introduced a user friendly drag-and-drop application development environment called App Designer. It’s similar to GUIDE and in future releases, App Designer and GUIDE will be integrated. Here we demonstrate how to use GUIDE tools to create GUIs.
Many GUI controls in GUIDE are quite straightforward and building a GUI model by employing GUI control tools is not difficult. We first launch the GUIDE tool and become familiar with its components and tools. Then we move on to working with GUI’s Property Inspector tools and modifying the operational behavior of the GUI blocks used in our model. Using this approach, after completing GUI modeling with GUI blocks, we save the model. MATLAB will automatically generate a script function file (M-file) that we modify according to our given GUI model requirements.
- 1.
Clearly define the specific functions that the anticipated GUI model should have and which tools and components you need. As always, it is best to start with a draft sketch of the GUI model on a piece of paper.
- 2.
Drag and drop all the necessary GUI components into the design area, and then modify and align them according to your needs and project requirements. Once every component is in place and adjusted with respect to each other, you can pull them into a Button Group (there is a component called Button Group), which gives you good flexibility for moving and aligning objects in the design area. Note that grouping components into a Button Group is optional.
- 3.
Rename or provide recognizable name “tags” to all components used in the model so you can easily identify them in later stages while editing scripts and M-files. Moreover, you may need to adjust and modify the color, font, and size of the components. Note that changing the color, font size, text type, size, and position of components in the model will not affect the execution/simulation results of the GUI model.
- 4.
Save the created work. It will be saved in two different file formats, one of which is *.fig (the Figure file) and the other is .m (the function file), containing a complete script of the model, including all nested callback functions for each GUI component.
- 5.
Write/edit a script that implements the performance of each GUI component in association with the other components. This step requires some additional programming work, which will be discussed in the following examples.
Example 1: Building a 2D Plot
Let’s take a very simple example of building a 2D plot of a cardinal sine function for a user’s input value ranges: .
Note
There is one major difference between Static Text and Edit Text. The user can edit an entry in an Edit Text block, but cannot do so in Static Text block.
In addition, we add an Axes block that displays a plot of computed values of the function sinc(x) according to our entries for xmin and xmax in the Edit Text blocks. We add a Push Button block that makes the built model (see Figure 3-5) compute the values of the function and display the results in the plot area.
Let’s make some changes to our GUI model blocks by altering their background color, size, font size, color, and type, and adjusting the positions of the blocks. Note that in the Static Text blocks, we edit the strings to be “Xmin” and “Xmax” in bold, 12.0 font size, and red and blue. In the Edit Text blocks, we remove their strings and make them empty. Moreover, we change their font size to 12.0, make them bold, and have a yellow background color.
Note
For the Edit Text blocks to have pre-defined values (e.g., -6, 0, 3.14, and 100), we need to insert these values into the "String" value of each Edit Text block.
Save the model and click on the Run button or press Ctrl+T from the keyboard. The new model, as shown in Figure 3-8, does not reflect any results yet. There is one important step that is still missing in the model’s coding part.
Note
While building a GUI model and editing the properties of blocks, it is important to rename each block distinctively. The blocks’ tags are required when modifying the callback functions of the GUI model.
In order to change the properties of several blocks simultaneously, select them all and then go to the Property Inspector to make changes.
Note that most of this script (SINC_fun.m is automatically generated by the GUI model when it is saved) won’t be changed and only one callback function will be edited. The callback functions have to be edited to make the GUI model perform the anticipated computations and display a plot figure. Note that every callback function has three parameter handles—hObject, evendata, and handles.
This simple example shows how easy it is to use GUIDE tools to build GUI models. Once the GUI model interface layout is complete and the components’ properties have been edited and saved, the M-file’s (function file’s) callback functions are generated. Subsequently, by editing only the required callback function or functions, we obtain the GUI model.
Example 2: Adding Functionality
Create an Exit/Quit button to close a GUI model window
Play a sound by recalling and executing another M-file (called SOUND_hear.m)
Display an image (called GC2011.jpg) in *.jpg/*.jpeg format
Display a message box with a message of "All Done Well Done!!!"
There are several ways to accomplish these tasks, one of which is to add a Push Button block and edit its callback function. We first go back to our GUI model editor and add one Push Button block. Change the Push Button’s properties (background color, font size and type, and string and tag) as we did previously. Now we rename the Push Button block to QUIT by changing its string; its name tag is renamed QUIT_button. Before saving the updated GUI model SINCfun.fig, we need to alter the name of the window. To do that, we need to double-click on the design area (the area outside of any blocks that opens the Property Inspector window) and then change the name tag from figure1 (the default) to GUI_window.
Subsequently, the built-in function run() executes the SOUND_hear.m file , which plays a sound wave. Another built-in function called image() displays the GC2011.jpg image , as shown in Figure 3-11. Finally, the msgbox() function displays the message: All Done Well Done!!!.
In this simple exercise, we have demonstrated how to associate GUI model buttons with other GUI blocks and M-files. Similarly, Simulink’s files, as well as any compatible applications with a MATLAB package, can be linked to GUI models.
Example 3: Solving a Quadratic Equation
Let’s take another example of creating a GUI model that solves a quadratic equation for any given coefficients for a, b, and c and displays a plot for the user’s specified value ranges of the variable x. The quadratic equation is formulated by ax2 + bx + c = 0 and if the numerical values of a, b, and c are given, we can compute the roots of the given equation numerically. This exercise is completed in two stages, building the GUI interface and editing the callback functions.
Building the GUI
We start again with a blank GUI window and choose a Panel block, onto which we drag and drop several blocks, such as Static Text, Edit Text, Push Button, and Axes. There is a good reason for employing the Panel block when building a GUI model. It helps you manipulate all the GUI blocks within it and around the Design Area with respect to each other.
We place the blocks in a, b, c order and then compute the results for D (discriminant), the root for x1 and x2, and the Push Button block to make the GUI model compute the discriminant, root x1, and root x2 values. After that, we edit the block properties by changing the font size, type, string, tag and background color of each block. Moreover, we edit the user’s entry blocks for xmin and xmax and use a Push Button block to plot the computation results in 2D. In addition, we change the name of the panel window to “Quadratic Equation Solver” by double-clicking on the Design Area and changing the Title in the Property Inspector. Figure 3-12 shows our completed GUI model window.
Note
In this GUI model (shown in Figure 3-12), the component names are not shown in order to save space in the palette window. You can turn them on/off by choosing File ➤ Preferences ➤ GUIDE ➤ Show Names in Component Palette.
Note that in the GUI model shown in Figure 3-12, the following properties of the blocks are altered: in Static Text blocks, such as “a”, “b”, “c”, “x1”, “x2”, “Xmin” and “Xmax”, the string, font size and type, and background color are changed. The properties of the three Static Text blocks used to display the computation results for Discriminant, x1, and x2 are altered. For instance, for the Static Text block for the Discriminant value display, background color, font type, size, string and tag are also changed. Its string is changed to be an empty space and its tag is renamed to D.
The background color, font type, size, string, and tag of the Static Text blocks used to display the values of x1 and x2 are altered. The strings are set to be empty and the tags are renamed to x1 and x2, for x1 and x2, respectively. There are two Push Button blocks used to solve the given equation (based on a, b, c) and to display the plot of the given quadratic equation with respect to the user entries for Xmin and Xmax.
The first Push Button block’s string is changed to SOLVE and its tag is SOLVE_eqn , and the second Push Button string is called PLOT and its tag is called PLOT_eqn . As stated above, tags are vital and require careful attention when editing or rewriting sub-functions in the M-file of the GUI model.
Editing the Callback Functions
Note that in the sub-function SOLVE_eqn_Callback, we use the get() command to obtain string values of a, b, c and convert them into numerical data with str2double(). Using the set() command , the computed values of D, x1, and x2 are assigned to D, x1, and x2 in order to display them in their respective Static Text blocks called “D”, “x1”, and “x2”. In the latter sub-function, we obtain the numerical values of a, b, and c with the get() command. We run the whole M-file called QUAD_eqn_SIM.m by clicking the Run button or calling the file from the command window (for example −3x2 + 5x + 1 = 0) and then plot the given equation for x = −1…3.
Note that in the SOLVE_eqn_Callback callback function, if the discriminant is D ≥ 0, then the computed roots will be also plotted. Moreover, there are several plot tools used here (hold on, legend, markersize, and markerfacecolor) that are explained in detail in Chapter 6.
Misspelled tag names of blocks that are recalled within sub-functions or set values to display in a GUI model window
Necessary conversion operators (such the get() and set() operators) are not employed appropriately within sub-functions for numerical calculations
Editing the wrong sub-functions (callback functions) of buttons to make a GUI model perform its aimed operations
In order to avoid these common mistakes, it is recommended to choose tag names carefully and double-check their names while writing and editing nested callback functions. Another recommendation is to write down all the tag names and type them in with care. When converting variable values from one type to another with the get() and set() operators, look at the task specifics. For instance, what type of data is needed for processing, and by which handle names (such as handles.WHAT) are values of variables or data obtained. There are several ways to avoid editing the wrong callback functions. One is to look up an assigned name tag for each button that makes the GUI model perform its anticipated operations. MATLAB automatically assigns a sub-function name to every operational button and entry block with its given name tag (a given name tag by a user) with a underscore sign and callback(). For instance, if an operational button’s name tag is PLOT_all, it will have an assigned sub-function called PLOT_all_Callback(hObject, eventdata, handles) . Another approach, after saving the GUI model and the automatically generated M-file, is to click on an operational button (e.g., a push button) in a GUI model design window. Then right-click and choose View Callbacks ➤ Callback to directly reach the right sub-function subject to edit.
GUI Dialogs and Message Boxes
MATLAB has a few of commands that create/call ready-to-use popup dialog boxes, including Error, Warning, Help, Information, User Entry Input dialog, and so forth. They can be created without writing scripts and callback functions or building GUIs. One of the most common purposes of these message boxes is to deliver messages to the users. In general, creating these popup message boxes is straightforward and requires only one command. The dialog and message boxes (except for the user input box) can all be called and generated with one general command: errordlg(), warndlg(), helpdlg(), and msgbox(). On the other hand, a user input dialog box requires several commands, such as the name of the input dialog, the input dialog window title/message, and the input dialog window. Let’s look at a few examples to see how to create these message boxes, a user entry dialog window, and an entry status box.
Error Dialog
General command syntax: errordlg('Add Notes')
Warning Message
General command syntax: warndlg('Add Notes')
F1 Help/Message Box
Note that CreateStruct, used in this example, is a variable type of struct that creates a structure type of variable with two fields of a character type —called WindowStyle with the value of replace and Interpreter with the value of tex. They are recognized automatically by MATLAB. Without creating the CreateStruct variable with its two fields, WindowStyle and Interpreter, the equation would be displayed as shown in the message box: f(α) = ecos(ωα)
General Syntax
Input Dialog
Question Dialog
Let’s look at more involved example that has several choices.
Making a Choice
Step 0. You are in a café and a waiter comes up to take your order.
Step 1. You decide between coffee, tea, and chocolate cake.
Step 2. The waiter responds that they don’t actually carry tea and are out of chocolate cake.
Step 3. You then choose your coffee type: Normal, Strong, or Special (your taste).
Step 4. You taste and grade the coffee.
Step 5. You pay the bill and leave a tip.
Note that in this script, we used MATLAB’s built-in function exist, which verifies whether a specific variable exists in the workspace. It uses the command syntax of exist('N', 'var') to determine whether the variable N is available in the workspace. It can also be used to verify whether any specific file exists in the current directory. For example, exist('MY_fun.c', 'file') checks whether the file called MY_fun.c is present in the current directory of MATLAB. The output of the built-in function exist() can be 0, 1, or 2. The 0 means the variable or file does not exist, 1 means the variable exists, and 2 means the file exists in the current directory.
When the script is executed, two message boxes (H1 and H2) are displayed for two to three seconds, and then closed automatically. Then the next question dialog box pops up and you need to choose Coffee, Tea, or Chocolate Cake.
Depending on your selection, other options and responses will appear. If you select Coffee, the question dialog (CA) will pop up and ask you to select your coffee type: Normal, Strong, or Special.
If you select Normal or Strong in the dialog box (CA), there will be popup box displaying the contents of your selected coffee in terms of coffee, milk, and sugar. If you select the Special type of coffee, you need to input (input dialog ANS) the amount of coffee, milk, and sugar you want in your coffee.
The message box (OK) pops up and closes down automatically after five seconds. Finally, the waiter asks you how your coffee tasted.
Based on your answer, you get the help dialog box indicating how much to pay, including the tip.
If you select Tea, the warning dialog box (H3) will pop up and close down automatically after two seconds,. If you choose Chocolate Cake, the error dialog (H4) will pop up and close down automatically in two seconds.
The last message box (H5) is displayed if you select Tea or Chocolate Cake in the first step.
These message and dialog boxes can also be employed within function files in a very similar manner.
Providing Input to an Equation
This simple numerical simulation exercise computes the values of a mathematical equation by writing a number to the function file: F = ecos(ωt).
No input, whereby the default values are taken
One input, ωn or t, whereby the missing argument takes the default values
Two inputs, ωn and t, whereby an error dialog pops up.
These Warning and Error dialog boxes are displayed.
This concludes our brief discussion of GUI tools and functions. These tools are very handy and can be associated with M/MLX-files and function files to make scripts more user friendly with GUI tools.