© Sulaymon Eshkabilov 2019
S. EshkabilovBeginning MATLAB and Simulinkhttps://doi.org/10.1007/978-1-4842-5061-7_3

3. Graphical User Interface Model Development

Sulaymon Eshkabilov1 
(1)
Fargo, United States
 

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

There are three principal groups of elements necessary to build a MATLAB GUI model. They are components, figures, and callbacks.
  • 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.

We can launch the GUIDE application by typing guide in the command window or choosing ../images/471979_1_En_3_Chapter/471979_1_En_3_Figa_HTML.jpg ➤ App ➤ GUIDE from the menu bar. Subsequently, the GUIDE Quick Start window appears, as shown in Figure 3-1.
../images/471979_1_En_3_Chapter/471979_1_En_3_Fig1_HTML.jpg
Figure 3-1

GUIDE Quick Start window

From these options, we can select a blank GUI (the default) or the ready-to-use example models of MATLAB, which are GUI with UIcontrols, GUI with Axes and Menu, or the Modal Question Dialog. When we choose Blank GUI (Default), the blank window shown in Figure 3-2 (named untitled.fig by default) will open.
../images/471979_1_En_3_Chapter/471979_1_En_3_Fig2_HTML.jpg
Figure 3-2

GUI figure window components without names

From this GUI layout window (Figure 3-2), we can start working. We can see the name tags of the GUI components and tools by selecting Show Names on Component Palette from the the MATLAB GUIDE Preferences. With this adjustment, the components will appear with their name tags, as shown in Figure 3-3.
../images/471979_1_En_3_Chapter/471979_1_En_3_Fig3_HTML.jpg
Figure 3-3

GUI components with name tags displayed

The GUI window shown in Figure 3-4 is composed of the GUI components, the design area, and the menu tools called Align Objects, Menu Editor, Tab Order Editor, etc. Once the GUI window is open, we can start building our GUI model by dragging the desired GUI components and dropping them into the design area (see Figure 3-4). We can resize and align the GUI components in our design area by clicking and dragging with a mouse or by using the right mouse button options or the Property Inspector, Align Objects, and other menu bar tools. Moreover, we can edit properties of the GUI components by clicking on the Editor and add menu tools to the GUI by clicking on the Toolbar Editor.
../images/471979_1_En_3_Chapter/471979_1_En_3_Fig4_HTML.jpg
Figure 3-4

The GUI GUIDE tool window and its menu bar

There are several basic steps required to build a GUI model:
  1. 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. 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. 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. 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. 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: $$ mathit{operatorname{sinc}}left(pi x
ight)=frac{mathit{sin}left(pi x
ight)}{pi x} $$.

By dragging and dropping the Push Button, Static Text, Edit Text, and Axes blocks, we start building the interface of the GUI model, as shown in Figure 3-5. After adjusting all the blocks in the GUI model with respect to each other, we can edit their properties by double-clicking on each block or using the Property Inspector option via the right mouse. Note that Static Text serves as information to show the input entry names: Xmin and Xmax. The values of Xmin and Xmax represent boundary values of the variable and can be defined in the Edit Text blocks.
../images/471979_1_En_3_Chapter/471979_1_En_3_Fig5_HTML.jpg
Figure 3-5

Necessary blocks selected and placed onto the GUI model area

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.

In order to make our GUI model more informative, legible, and user friendly, we can edit each block by altering the font size, color, background color, and so forth. There are many properties for each individual block that can be altered. For instance, we can change the front color, background color, font type, size and color, position, size, string, name, and a few other properties (see Figure 3-6). Among these properties, there are two main ones (see Figure 3-6) that we have to pay close attention to. The first one is tag and it’s the name of a block and has to be a distinctive name. The second property is string and it’s used to display fixed text or an empty space. The string is displayed in the GUI model.
../images/471979_1_En_3_Chapter/471979_1_En_3_Fig6_HTML.jpg
Figure 3-6

Property Inspector window to edit properties of blocks

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.

../images/471979_1_En_3_Chapter/471979_1_En_3_Figb_HTML.jpg

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.

The Push Button’s background color, font size, type, string, and tag names are modified. Its string is altered to "PLOT" and its tag is renamed to PLOTsinc. Figure 3-7 shows the completed GUI model.
../images/471979_1_En_3_Chapter/471979_1_En_3_Fig7_HTML.jpg
Figure 3-7

The completed GUI model with all modified buttons and components

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.

../images/471979_1_En_3_Chapter/471979_1_En_3_Fig8_HTML.jpg
Figure 3-8

The created SINC function plot GUI

MATLAB saves the model in two file formats—SINC_fun.m (the function file) and SINC_fun.fig (the GUI figure). All the callback functions of the buttons used in SINCfun.m are shown here:
function varargout = SINCfun(varargin)
% SINCFUN MATLAB code for SINCfun.fig
% SINCFUN, by itself, creates a new SINCFUN or raises the existing
% singleton*.
...
% Begin initialization code - DO NOT EDIT
gui_Singleton = 1;
gui_State = struct('gui_Name', mfilename, ...
 'gui_Singleton', gui_Singleton, ...
 'gui_OpeningFcn', @SINCfun_OpeningFcn, ...
 'gui_OutputFcn', @SINCfun_OutputFcn, ...
 'gui_LayoutFcn', [] , ...
 'gui_Callback', []);
if nargin && ischar(varargin{1})
 gui_State.gui_Callback = str2func(varargin{1});
end
if nargout
 [varargout{1:nargout}] = gui_mainfcn(gui_State, varargin{:});
else
 gui_mainfcn(gui_State, varargin{:});
end
% End initialization code - DO NOT EDIT
% --- Executes just before SINCfun is made visible.
function SINCfun_OpeningFcn(hObject, eventdata, handles, varargin)
% This function has no output args, see OutputFcn.
...
function Xmax_Callback(hObject, eventdata, handles)
% hObject handle to Xmax (see GCBO)
...
% --- Executes on button press in PLOTsinc.
function PLOTsinc_Callback(hObject, eventdata, handles)
% hObject handle to PLOTsinc (see GCBO)
...

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.

While editing/writing callback functions, we can look up the properties of handles using the get() function and assign or change any property of the handles by using the set() function. Note that in the SINCfun.m model, there is only one callback function that has to be edited—PLOTsinc_Callback(hObject, eventdata, handles). The PLOTsinc_Callback callback function invokes the PLOT button, which is named with a tag name of PLOTsinc. The PLOTsinc tag name is given to the PLOT button via the Property Inspector while building the GUI model. This callback function computes sinc(πx) by taking user entries for xmin and xmax and plotting the computed results. To edit the PLOTsinc_Callback(hObject, eventdata, handles) callback function, we first convert the entries for Xmin and Xmax from the string format into the double format in the following way:
Xmin=str2double(get(handles.Xmin, 'string'));
Xmax=str2double(get(handles.Xmax, 'string'));
The get() command collects data from handles.Xmin and handles.Xmax as a string and then str2double() converts them into a numerical format. Double-formatted values of Xmin and Xmax are taken to generate equally spaced values of the variable x, which are then taken to compute f(x) = sinc(πx) and plot the results using the following commands:
x=linspace(Xmin, Xmax, 200); f=sinc(x*pi); plot(x, f, 'b');
grid on
title('sinc(pi*x) = sin(pi*x)/(pi*x) ')
xlabel('x'),ylabel('f(x)=sinc(pi*x)'),
axis([Xmin, Xmax, -.25, 1.1])
Finally, the edited callback function PLOTsinc_Callback(hObject, eventdata, handles) contains the following:
function PLOTsinc_Callback(hObject, eventdata, handles)
Xmin=str2double(get(handles.Xmin, 'string'));
Xmax=str2double(get(handles.Xmax, 'string'));
x=linspace(Xmin, Xmax, 200);
f=sinc(x*pi);
plot(x, f, 'b'); grid on
title('sinc(pi*x) = sin(pi*x)/(pi*x) ')
xlabel('x'),ylabel('f(x)=sinc(pi*x)'),
axis([Xmin, Xmax, -.25, 1.1])
As noted, this is the only part of the M-file SINCfun.m that we have edited in order to make the model compute and plot the sinc(πx) function with a single click in the GUI model. We save the SINCfun.m file and execute it by using ../images/471979_1_En_3_Chapter/471979_1_En_3_Figc_HTML.jpg in M-file editor or by pressing F5 from the keyboard. When we run SINCfun.m, the SINCfun.fig GUI model pops up. We enter two entries—Xmin =  − 5 and Xmax = 6—and click the PLOT button. The results of the function are computed and plotted, as shown in Figure 3-9. Note that the value of Xmax must be larger than the value of Xmin; otherwise, there will be an error.
../images/471979_1_En_3_Chapter/471979_1_En_3_Fig9_HTML.jpg
Figure 3-9

The GUI model to plot the sinc(πx) function

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

Let’s look at four more options for our GUI model (Figure 3-9):
  • 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.

../images/471979_1_En_3_Chapter/471979_1_En_3_Figd_HTML.jpg
We save the GUI model and execute it. After that, we edit the last automatically added callback function called QUIT_button_Callback(hObject, eventdata, handles) by adding the following to it. The built-in MATLAB function called delete() halts the whole process and shuts the window.
function QUIT_button_Callback(hObject, eventdata, handles)
delete(handles.GUI_window)
run('SOUND_hear.m'); A=imread('GC2011.jpg'); image(A);
msgbox('All Done Well Done!!!')
Figure 3-10 shows the updated GUI model. We can test it with two numerical entries for Xmin and Xmax and then click on the QUIT button. After pressing QUIT, the GUI window SINCfun.fig is closed.
../images/471979_1_En_3_Chapter/471979_1_En_3_Fig10_HTML.jpg
Figure 3-10

The GUI model to display the sinc(πx) and quit options

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!!!.

The separate M-file called SOUND_hear.m contains the following scripts:
% SOUND_hear.m
% Three CHIRP signals to make a sound
t=0:1/1e4:10;
D0=chirp(t, 0, 10, 3000, 'quadratic');
D1=chirp(t, 0, 10, 4000, 'q',[],'convex');
D2=chirp(t, .001, 10, 5000, 'logarithmic');
y=[D0, D1, D2]; sound(y);
../images/471979_1_En_3_Chapter/471979_1_En_3_Fig11_HTML.jpg
Figure 3-11

Image file GC2011.jpg is displayed

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.

../images/471979_1_En_3_Chapter/471979_1_En_3_Fig12_HTML.jpg
Figure 3-12

Complete design of the GUI model window

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.

Up to this point, all we have worked with is within the GUI design window and the properties of our chosen blocks within the Property Inspector, which we did by double-clicking on each block individually. Another change that we made in this example was altering the panel window; we altered its background color, title, font type, and size. Finally, after completing all the changes in our GUI model, we saved it with the filename QUAD_eqn_SIM.fig (see Figure 3-13), which saved the QUAD_eqn_SIM.m automatically as well.
../images/471979_1_En_3_Chapter/471979_1_En_3_Fig13_HTML.jpg
Figure 3-13

Completed GUI model to compute roots and display a 2D plot of the quadratic equation

Editing the Callback Functions

The model shown in Figure 3-13 does not reveal any results when we click on the SOLVE or PLOT buttons. We edit and rewrite two callback functions of the M-file—QUAD_eqn_SIM.m. Note that all of the automatically generated comments are removed from the script.
function varargout = QUAD_eqn_SIM(varargin)
% QUAD_EQN_SIM MATLAB code for QUAD_eqn_SIM.fig
...
gui_Singleton = 1;
gui_State = struct('gui_Name', mfilename, ...
 'gui_Singleton', gui_Singleton, ...
 'gui_OpeningFcn', @QUAD_eqn_SIM_OpeningFcn, ...
 'gui_OutputFcn', @QUAD_eqn_SIM_OutputFcn, ...
 'gui_LayoutFcn', [] , ...
 'gui_Callback', []);
if nargin && ischar(varargin{1})
 gui_State.gui_Callback = str2func(varargin{1});
end
...
handles.output = hObject;
guidata(hObject, handles);
function varargout = QUAD_eqn_SIM_OutputFcn(hObject, eventdata, handles)
...
varargout{1} = handles.output;
function a_Callback(hObject, eventdata, handles)
...
function a_CreateFcn(hObject, eventdata, handles)
...
function b_Callback(hObject, eventdata, handles)
...
function b_CreateFcn(hObject, eventdata, handles)
...
function edit3_Callback(hObject, eventdata, handles)
...
function edit3_CreateFcn(hObject, eventdata, handles)
...
if ispc && isequal(get(hObject,'BackgroundColor'), get(0,'defaultUicontrolBackgroundColor'))
 set(hObject,'BackgroundColor','white');
end
function Xmin_Callback(hObject, eventdata, handles)
...
function Xmin_CreateFcn(hObject, eventdata, handles)
...
function Xmax_Callback(hObject, eventdata, handles)
...
function Xmax_CreateFcn(hObject, eventdata, handles)
...
if ispc && isequal(get(hObject,'BackgroundColor'), get(0,'defaultUicontrolBackgroundColor'))
 set(hObject,'BackgroundColor','white');
end
function SOLVE_eqn_Callback(hObject, eventdata, handles)
...
function PLOT_eqn_Callback(hObject, eventdata, handles)
...
The callback functions that we will edit are PLOT_eqn_Callback(hObject, eventdata, handles) and SOLVE_eqn_Callback(hObject, eventdata, handles) . These callback functions make the GUI model compute and display discriminant, two real-valued roots in pre-defined blocks and display a 2D plot according to our entries for Xmin and Xmax. Here are the edited callback functions for the two push buttons called SOLVE and PLOT:
...
function SOLVE_eqn_Callback(hObject, eventdata, handles)
a=str2double(get(handles.a, 'string'));
b=str2double(get(handles.b, 'string'));
c=str2double(get(handles.c, 'string'));
D=b^2-4*a*c;
if D>0 % There are two real valued roots;
x1=(-b+sqrt(D))/(2*a);
x2=(-b-sqrt(D))/(2*a);
elseif D==0 % There is a unique root;
 x1=-b/(2*a);
 x2=x1;
else % No real valued roots exist;
 x1='No Root';
 x2='No Root';
end
D=num2str(D); set(handles.D, 'string', D);
x1=num2str(x1); set(handles.x1, 'string', x1);
x2=num2str(x2); set(handles.x2, 'string', x2);
function PLOT_eqn_Callback(hObject, eventdata, handles)
a=str2double(get(handles.a, 'string'));
b=str2double(get(handles.b, 'string'));
c=str2double(get(handles.c, 'string'));
D=str2double(get(handles.D, 'string'));
x1=str2double(get(handles.x1, 'string'));
x2=str2double(get(handles.x2, 'string'));Xmin=str2double(get(handles.Xmin, 'string'));
Xmax=str2double(get(handles.Xmax, 'string'));
x=linspace(Xmin, Xmax, 200); y=a*x.^2+b*x+c;
plot(x, y, 'r-', 'linewidth', 1.5); xlabel('x'), ylabel('y = ax^2+bx+c')
if D>=0   % Roots x1 and x2 will be plotted if the equation has real roots
hold on  % Plot is held if D>=0
plot(x1, 0, 'rs', x2, 0, 'gd', 'markersize', 7, 'markerfacecolor', 'y')
legend('plot of quad. eqn', 'root: x_1', 'root: x_2')
end
title(['Plot of:  ' num2str(a)  'x^2 + '  num2str(b)  'x + '  num2str(c)  ' = 0']); grid on

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.

Figure 3-14 shows the final GUI model with its results for the given example −3x2 + 5x + 1 = 0 and for x = −1…3.
../images/471979_1_En_3_Chapter/471979_1_En_3_Fig14_HTML.jpg
Figure 3-14

The GUI model to compute roots of a quadratic equation and plot its values with user entries for Xmin and Xmax

Let’s review some of the most common errors made while editing and rewriting sub-functions. They are:
  • 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')

Example:
errordlg(['Time is gone!' 'Today is ' date])
../images/471979_1_En_3_Chapter/471979_1_En_3_Fige_HTML.jpg

Warning Message

General command syntax: warndlg('Add Notes')

Example :
warndlg(['Outside temperature is ' num2str(-20) ' C; thus, be dressed up accordingly!!!'])
../images/471979_1_En_3_Chapter/471979_1_En_3_Figf_HTML.jpg

F1 Help/Message Box

General command syntax:
helpdlg('Add Notes')
Example:
helpdlg('What is your problem?', 'This is a help line');
../images/471979_1_En_3_Chapter/471979_1_En_3_Figg_HTML.jpg
A second example:
CreateStruct.WindowStyle='replace';
CreateStruct.Interpreter='tex';
msgbox('f(alpha) = e^{cos(omega*alpha)}','Function: ',CreateStruct);

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(ωα)

../images/471979_1_En_3_Chapter/471979_1_En_3_Figh_HTML.jpg

Finally:
msgbox('copyright by NDSU', 'Copyright',CreateStruct)
../images/471979_1_En_3_Chapter/471979_1_En_3_Figi_HTML.jpg

General Syntax

There are alternative ways to create help/message/error/warning messages. The general command syntax is:
HM = msgbox('Message', 'Box Title', 'Icon')
Here is just a message box:
msgbox('Hello World', 'My Message')

../images/471979_1_En_3_Chapter/471979_1_En_3_Figj_HTML.jpg

Here’s a warning message:
msgbox('Hello World', 'My Message', 'warn')
../images/471979_1_En_3_Chapter/471979_1_En_3_Figk_HTML.jpg
Here’s a message box with an error sign:
msgbox('Hello Students', 'My Message', 'error')

../images/471979_1_En_3_Chapter/471979_1_En_3_Figl_HTML.jpg

Here’s a message box with an information sign:
msgbox('Hello Students', 'My Message', 'help')

../images/471979_1_En_3_Chapter/471979_1_En_3_Figm_HTML.jpg

Input Dialog

General command syntax:
ANSWER = inputdlg(PROMPT,NAME)
Here is a short script:
Enter1={'Enter # of FS terms to evolve & Hit [ok] & Wait: '}; % Message
Name1='Input for TERMS of Fourier Series'; % Dialog box name
Numlines = 1; % Number of lines for Input dialog
ANSWER=inputdlg(Enter1, Name1, Numlines); % Generate and Read Input Dialog
[n status] = str2num(ANSWER{1}); % Picks up the user entry under variable name of n
../images/471979_1_En_3_Chapter/471979_1_En_3_Fign_HTML.jpg

Question Dialog

General command syntax:
|ButtonName = questdlg('Your Question ...', 'Question?', 'Option1', 'Option2', ....)
An example:
YA= questdlg('Select your answer to the question: "How do you feel?" ','Question', 'Superb', 'I Can Work for a while', 'Tired a bit', ' ')
../images/471979_1_En_3_Chapter/471979_1_En_3_Figo_HTML.jpg

Let’s look at more involved example that has several choices.

Making a Choice

You are in a café and would like to make a purchase. You would like to choose from the menu: coffee, tea, or some sweets. The café has some shortages that you are not aware of. The message and dialog boxes such as warning, help, input, or error messages need to be displayed according to your order and the café shortages. Here are the steps to be implemented in this script.
  • 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.

Here is the answer script:
clearvars
% It is time for coffee, let's go to a cafe ...
% Step 0
H1 = msgbox('You are in a cafe and ordering coffee of your taste', 'Cafe');
pause(2), delete(H1)
% Step 1. Ordering your coffee
H2 = msgbox('What can I do for you today? Do you want coffee or sweets',...
 'Waiter has arrived');
pause(3), delete(H2)
% Answer what you like to have
YA= questdlg('Your answer: "Do you want coffee or sweets?" ','Question', ...
 'Coffee', 'Tea', 'Chocolate Cake', ' ');
switch YA
 case 'Coffee'
 CA = questdlg('Your answer: "OK. What kind of coffee?" ','Question', ...
 'Normal', 'Strong', 'Special', ' ');
 case 'Tea'
 H3=warndlg(['Sorry! We do not serve' ' Tea. Maybe something else?']); pause(2)
 delete(H3)
 case 'Chocolate Cake'
 H4=errordlg(['Very Sorry!' 'No cakes Left ']); pause(2)
 delete(H4)
end
Response=exist('CA', 'var');
if Response ==1
 switch CA
 case 'Normal'
 HN=warndlg(['Normal coffee is', ...
 ' 3 tea-spoons of coffee+3 Table-spoons of Milk+1 tea-spoon of sugar']);
 pause(3), delete(HN)
 case 'Strong'
 HS=warndlg(['Strong coffee is', ...
 ' 4 tea-spoons of coffee+2 Table-spoons of Milk+2 tea-spoon of sugar']);
 pause(3), delete(HS)
 case 'Special'
HS = msgbox('Select: how much coffee, milk and sugar to add?', 'Selection');
 pause(3), delete(HS)
 Call = 'Order your coffee';
 Selection = {'how many tea-spoons of coffee: ',...
 'how many tablespoons of milk: ', 'how many teaspoons of sugar: '};
 n_lines=[1, 13];
 ANS=inputdlg(Selection, Call, 1, {' ', ' ', ' '});
 end
 OK = msgbox('You have had your coffee','You are about to leave ');
 pause(5), delete(OK)
 PB= questdlg('Waiter asks: "How was the coffee?" ','Question', ...
 'Just Superb', 'Nice', 'Umm...but OK', ' ');
 switch PB
 case 'Just Superb'
 helpdlg('Thank you so much! 4$+1$ (tips)', 'Here is the payment');
 case 'Nice'
 helpdlg('Thanks! 4$+0.50$ (tips)', 'Here is the payment');
 case 'Umm...but OK'
 helpdlg('Thank you! 4$ (No-tips)', 'Here is the payment');
 end
else
 H5 = msgbox('Bye - Bye! See you next time!', 'Waiter leaves');
 pause(4), delete(H5)
end

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.

../images/471979_1_En_3_Chapter/471979_1_En_3_Figp_HTML.jpg

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.

../images/471979_1_En_3_Chapter/471979_1_En_3_Figq_HTML.jpg

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.

../images/471979_1_En_3_Chapter/471979_1_En_3_Figr_HTML.jpg

The message box (OK) pops up and closes down automatically after five seconds. Finally, the waiter asks you how your coffee tasted.

../images/471979_1_En_3_Chapter/471979_1_En_3_Figs_HTML.jpg

Based on your answer, you get the help dialog box indicating how much to pay, including the tip.

../images/471979_1_En_3_Chapter/471979_1_En_3_Figt_HTML.jpg

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).

The varying inputs are as follows:
  • No input, whereby the default values $$ {omega}_n=13;t=0:frac{pi }{100}:pi; $$ 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.

Here is the complete answer script of this exercise:
function F = ERR(varargin)
% HELP. ERR.m simulates how to employ ERROR dialog box
warndlg('Note that this is a varargin function file ');
if nargin == 0
 omega = 13; t = 0:pi/100:pi;F = exp(cos(omega*t)); plot(t, F, 'bo--'), shg
elseif nargin == 1 && numel(varargin{1})==1
omega=varargin{1}; t = 0:pi/100:pi;F = exp(cos(omega*t)); plot(t, F, 'bo--')
elseif nargin == 1 && numel(varargin{1})>1
 t = varargin{1}; omega=13;F = exp(cos(omega*t)); plot(t, F, 'bo--')
elseif nargin ==2 && numel(varargin{1})==1
omega=varargin{1}; t =varargin{2};F = exp(cos(omega*t)); plot(t, F, 'bo--')
elseif nargin == 2 && numel(varargin{1})>1
omega=varargin{2}; t = varargin{1};F = exp(cos(omega*t)); plot(t, F, 'bo--')
else
errordlg(['Wrong Number of Inputs!' num2str(nargin) ' are too many INPUTs'])
 disp('No OUPUTS')
F=warndlg(['No OUTPUTS because ' num2str(nargin) ' are too many INPUTS']);
end
end
Let’s simulate the above function file (ERR.m) from the command window:
>> omega = 13; t = 0:pi/100:pi; OmegaN=13;
>> F = ERR(omega, OmegaN, t);
No OUPUTS

These Warning and Error dialog boxes are displayed.

../images/471979_1_En_3_Chapter/471979_1_En_3_Figu_HTML.jpg
../images/471979_1_En_3_Chapter/471979_1_En_3_Figv_HTML.jpg

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.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.138.69.163