Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                
0% found this document useful (0 votes)
1 views

UNIT-5 MATLAB

Uploaded by

l50711876
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
1 views

UNIT-5 MATLAB

Uploaded by

l50711876
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 26

UNIT-V

SOLUTION OF ORDINARY
DIFFERENTIAL EQUATIONS (ODES) &
GRAPHICAL USER INTERFACE (GUI)

Solution of Ordinary differential Equations (ODEs)-The 4th order Runge-kutta Method, ODE
Solvers in MATLAB, Solving First–order equations using ODE23 and ODE45. Structures and
Graphical user interface (GUI): Advanced data Objects, how a GUI works, Creating and
displaying a GUI. GUI components, Dialog Boxes.

INTRODUCTION- ORDINARY DIFFERENTIAL EQUATIONS (ODES)


 There are 2 types of derivatives:
𝑑𝑣
1. Ordinary Derivatives( )- v is a function of one independent variable
𝑑𝑡
𝑑𝑢
2. Partial Derivatives( ) - u is a function of more than one independent variable
𝑑𝑦

Differential Equations: The classification of differential equations are given below:

Ordinary Differential Equations


 Ordinary Differential Equations (ODEs) involve one or more ordinary derivatives
of unknown functions with respect to one independent variable
Examples :
dv(t )
 v (t )  e t
dt
d 2 x (t ) dx(t )
2
5  2 x (t )  cos(t )
dt dt
 Here t is an independent variable & x(t) unknown function.
 The order of an ordinary differential equation is the order of the highest order
derivative.
Examples :
dx(t ) First order ODE
 x (t )  e t
dt
d 2 x (t ) dx(t ) Second order ODE
 5  2 x (t )  cos(t )
dt 2 dt
3
 d 2 x (t )  dx(t )

 
  dt  2 x (t )  1
4
Second order ODE
 dt 2 
 A solution to a differential equation is a function that satisfies the equation.

 Linear ODE
 An ODE is linear if The unknown function and its derivatives appear to power one
 No product of the unknown function and/or its derivatives
Examples :
dx(t ) ---Linear ODE
 x (t )  e t
dt
d 2 x(t ) dx(t )
2
5  2t 2 x (t )  cos(t )
dt dt ----Linear ODE
3
 d 2 x (t )  dx(t )
 2
   x (t )  1 -----Non-linear ODE
 dt  dt

 In the point of solution of ordinary differential equations we can have many


functions that satisfy the differential equation.
Uniqueness of a Solution

 In order to uniquely specify a solution to an nth order differential equation we need


n conditions.
 Auxiliary Conditions
 There are 2 types of conditions.
1. Initial Conditions: All conditions are at one point of the independent variable
2. Boundary Conditions: The conditions are not at one point of the independent
variable

Classification of ODEs
ODEs can be classified in different ways:
• Order
• First order ODE
• Second order ODE
• Nth order ODE
• Linearity
• Linear ODE
• Nonlinear ODE
• Auxiliary conditions
• Initial value problems
Boundary value problems
 There are 2 types of solutions for solving of ordinary differential solutions:
1. Analytical solutions:

 Analytical Solutions to ODEs are available for linear ODEs and special classes of
nonlinear differential equations.
2. Numerical solutions:
 Numerical methods are used to obtain a graph or a table of the unknown function.
 Most of the Numerical methods used to solve ODEs are based directly (or
indirectly) on the truncated Taylor series expansion.
Classification of the Methods
Numerical Methods for Solving ODE are Two. These are:
1. Single-Step Methods: Estimates of the solution at a particular step are entirely
based on information on the previous step.
2. Multiple-Step Methods: Estimates of the solution at a particular step are based on
information on more than one step.

SOLUTION OF ORDINARY DIFFERENTIAL EQUATIONS (ODES)


• Taylor’s series is a numerical method used for solving differential equations and
is limited by the work to be done in finding the derivatives of the higher-order.
• To overcome this, we can use a new category of numerical methods called Runge-
Kutta methods to solve differential equations.
• These will give us higher accuracy without performing more calculations.
• These methods coordinate with the solution of Taylor’s series up to the term in
hr, where r varies from method to method, representing the order of that method.
• One of the most significant advantages of Runge-Kutta formulae is that it requires
the function’s values at some specified points.
The Runge-kutta Method
• Consider an ordinary differential equation of the form
dy/dx = f(x, y) with initial condition y(x0) = y0.
• For this, we can define the formulas for Runge-Kutta methods as follows.
1st Order Runge-Kutta method
• y1 = y0 + hf(x0, y0) = y0 + hy’0 { since y’ = f(x, y) }
2nd Order Runge-Kutta method
y1 = y0 + (½) (k1 + k2)
Here,
k1 = hf(x0, y0)
k2 = hf(x0 + h, y0 + k1)
3rd Order Runge-Kutta method
• y1 = y0 + (⅙) (k1 + 4k2 + k3)
Here,
k1 = hf(x0, y0)
k2 = hf[x0 + (½)h, y0 + (½)k1]
k3 = hf(x0 + h, y0 + k1) such that k1 = hf(x0 + h, y0 + k1)

THE 4TH ORDER RUNGE-KUTTA METHOD:


The most commonly used Runge Kutta method to find the solution of a differential
equation is the RK4 method, i.e., the fourth-order Runge-Kutta method.
 The Runge-Kutta method provides the approximate value of y for a given point x.
 Only the first order ODEs can be solved using the Runge Kutta RK4 method.
 Runge-Kutta Fourth Order Method Formula
 The formula for the fourth-order Runge-Kutta method is given by:
y1 = y0 + (⅙) (k1 + 2k2 + 2k3 + k4)
Here,
k1 = hf(x0, y0)
k2 = hf[x0 + (½)h, y0 + (½)k1]
k3 = hf[x0 + (½)h, y0 + (½)k2]
k4 = hf(x0 + h, y0 + k3)
Example 1:
Consider an ordinary differential equation dy/dx = x2 + y2, y(1) = 1.2. Find y(1.05)
using the fourth order Runge-Kutta method.
Solution:
Given, dy/dx = x2 + y2, y(1) = 1.2
So, f(x, y) = x2 + y2
x0 = 1 and y0 = 1.2, h = 0.05
Let us calculate the values of k1, k2, k3 and k4.
k1 = hf(x0, y0) = (0.05) [x02 + y02] = (0.05) [(1)2 + (1.2)2]
= (0.05) (1 + 1.44) = (0.05)(2.44) = 0.122
k2 = hf[x0 + (½)h, y0 + (½)k1]
= (0.05) [f(1 + 0.025, 1.2 + 0.061)]
{since h/2 = 0.05/2 = 0.025 and k1/2 = 0.122/2 = 0.061}
= (0.05) [f(1.025, 1.261)]= (0.05) [(1.025)2 + (1.261)2]
= (0.05) (1.051 + 1.590) = (0.05)(2.641) = 0.1320
k3 = hf[x0 + (½)h, y0 + (½)k2]
= (0.05) [f(1 + 0.025, 1.2 + 0.066)] {since h/2 = 0.05/2 = 0.025 and k2/2 = 0.132/2
= 0.066}
= (0.05) [f(1.025, 1.266)] = (0.05) [(1.025)2 + (1.266)2]
= (0.05) (1.051 + 1.602) = (0.05)(2.653) = 0.1326
k4 = hf(x0 + h, y0 + k3)
= (0.05) [f(1 + 0.05, 1.2 + 0.1326)] = (0.05) [f(1.05, 1.3326)]
= (0.05) [(1.05)2 + (1.3326)2] = (0.05) (1.1025 + 1.7758)
= (0.05)(2.8783) = 0.1439
By RK4 method, we have;
y1 = y0 + (⅙) (k1 + 2k2 + 2k3 + k4)
y1 = y(1.05) = y0 + (⅙) (k1 + 2k2 + 2k3 + k4)
By substituting the values of y0, k1, k2, k3 and k4, we get;
y(1.05) = 1.2 + (⅙) [0.122 + 2(0.1320) + 2(0.1326) + 0.1439]
= 1.2 + (⅙) (0.122 + 0.264 + 0.2652 + 0.1439) = 1.2 + (⅙) (0.7951)
= 1.2 + 0.1325 = 1.3325

Exercise Problems:
1. Using the Runge-Kutta method of order 4, find y(0.2) if
dy/dx = (y – x)/(y + x), y(0) = 1 and h = 0.2.
2. Find the value of y(0.3) from the differential equation
dy/dx = 3ex + 2y; y(0) = 0, h = 0.3 by the fourth order Runge-Kutta method.
3. Using RK4 method to find y(0.2) and y(0.4) if dy/dx = 1 + y + x2; y(0) = 0.5

ODE Solvers in MATLAB


 There is a separate suite of ordinary differential equation solvers in MATLAB.
 MATLAB used to have two built-in functions for solution of ODEs

 ode23

 ode45
 The functions ode23 and ode45 are implementations of second-/third-order and
fourth-/fifth-order Runge-Kutta(RK) methods, respectively.
o ode45: It is based on an explicit Runge-Kutta (4, 5) formula and the
Dormand-Prince method.
o ode23: It is based on an explicit Runge-Kutta (2, 3) formula and the Bogacki
and Shampine method.

 We choose according to order of accuracy and the type of systems.


 MATLAB has several different ODE solvers for the numerical solution of ODEs:

 We choose according to order of accuracy and the type of systems (stiff or nonstiff).
 The MATLAB ODE solvers can be called as a function:
[T,Y] = odexx(@odefun,tspan,y0,options)
@odefun: Function handle of the ODE function
tspan: Interval of integration, [t0,tnal ].
y0: Initial conditions.
options: Optional parameters.
The ODE function odefun done by using the ODEs:
function [dy] = odefun(t, y, parameters)

INTRODUCTION-GRAPHICAL USER INTERFACE:


 A graphical user interface (GUI) is a pictorial interface to a program.
 A good GUI can make programs easier to use by providing them with a consistent
appearance and with intuitive controls such as pushbuttons, edit boxes, list
boxes, sliders, and menus.
 The GUI should behave in an understandable and predictable manner so that a
user knows what to expect when he or she performs an action.
Example: When a mouse click occurs on a pushbutton, the GUI should initiate the
action described on the label of the button.

5.1 HOW A GRAPHICAL USER INTERFACE WORKS


 A graphical user interface (GUI) provides the user with a familiar environment in
which to work.
 Graphical user interface (GUI) contains pushbuttons, toggle buttons, lists,
menus, text boxes.
 GUIs are harder for the programmer, because a GUI-based program must be
prepared for mouse clicks (or possibly keyboard input) for any GUI element at any
time.
 Such inputs are known as events, and a program that responds to events is said
to be event driven.
 The three principal elements required to create a MATLAB graphical user interface
are
i. Components
ii. Containers
iii. Callbacks
1. Components
 Each item on a MATLAB GUI (pushbuttons, labels, edit boxes, etc.) is a graphical
component.
 The types of components include
a. Graphical controls (pushbuttons, toggle buttons, edit boxes, lists, sliders, etc.)
b. static elements (text boxes)
c. menus
d. toolbars
e. axes
 Graphical controls and text boxes are created by the function uicontrol.
 Menus are created by the functions uimenu and uicontextmenu.
 Toolbars are created by function uitoolbar.
 Axes, which are used to display graphical data, are created by the function axes.
2. Containers
 The components of a GUI must be arranged within a container, which is a window
on the computer screen.
 The most common container is a figure.
 A figure is a window on the computer screen that has a title bar along the top and
that can optionally have menus attached.
 In the past, figures have been created automatically whenever we plotted data.
 Empty figures can be created with the function figure, and they can be used to
hold any combination of components and other containers.
 The other types of containers are panels (created by the function uipanel) and
button groups (created by the function uibuttongroup).
 Panels can contain components or other containers, but they do not have a title
bar and cannot have menus attached.
 Button groups are special panels that can manage groups of radio buttons or
toggle buttons to ensure that no more than one button in the group is on at any
time.
3. Callbacks:
 There must be some way to perform an action if a user clicks a mouse on a button
or types information on a keyboard.
 A mouse click or a key press is an event, and the MATLAB program must respond
to each event if the program is to perform its function.
 For example, if a user clicks on a button, then that event must cause the MATLAB
code that implements the function of the button to be executed.
 The code executed in response to an event is known as a callback.
 There must be a callback to implement the function of each graphical component
on the GUI.
 The basic GUI elements are summarized in Table 10.1, and some sample elements
are shown in Figure 5.1.
Component Created By Description
Containers
Figure figure It creates a figure, which is container that can hold
components and other containers. Figures are
separate windows that have title bars and can have
menus.
Panel uipanel It creates a panel, which is container that can hold
components and other containers. Unlike figures,
panels do not have title bars or menus. Panels can be
placed inside figures or other panels.
Button Group uibuttongroup It creates a button group, which is a special kind of
panel. Button groups automatically manage groups of
radio buttons or toggle buttons to ensure that only one
item of the group is on at any given time.
Graphical Controls
Pushbutton uicontrol A graphical element that implements a pushbutton. It
triggers the callback when clicked with a mouse.
Toggle Button uicontrol A graphical component that perform a toggle button.
A toggle button is either "on" or "off," and it change
state each time it is clicked. Each mouse button click
also triggers a callback.
Radio Button uicontrol A radio button is a type of toggle button that occur as
a small circle with a dot in the middle when it is "on."
Groups of radio buttons are used to perform mutually
exclusive choices. Each mouse click on a radio button
triggers a callback.
Checkbox uicontrol A checkbox is a type of toggle button that occur as a
small square with a check mark in it when it is "on."
Each mouse click on a checkbox triggers a callback.
Edit Box uicontrol An edit box displays a text string and allows the user
to modify the information presented. A callback is
triggered when the user presses the Enter key, or when
the user clicks on a different object with the mouse.
List Box uicontrol A list box is a graphical control that shows a series of
text strings. A customer may select one of the text
strings by single- or double-clicking on them. A
callback is triggered when the customer selects a
string.
Popup Menus uicontrol A popup menu is a graphical control that shows a
series of text strings in response to a mouse click.
When the popup menu is not clicked on, only the
currently selected string is clear.
Slider uicontrol A slider is a graphical control to adjust a value in a
smooth, regular fashion by dragging the control with a
mouse. Each slider modify triggers a callback.
Static Elements
Frame uicontrol It creates a frame, which is a rectangular box within a
figure. Frames are used to association sets of controls
together. Frames never trigger callbacks.
Text Field uicontrol It creates a label, which is a text string located at a
point on the figure. Text fields never trigger callbacks.
Menus, Toolbars, Axes
Menu Items uimenu It creates a menu item. Menu items trigger a callback
when a mouse button is released over them
Context uicontextmenu It creates a context menu, which is a menu that
Menus appears over a graphical object when a user right-
clicks the mouse on that object.
Toolbar uitoolbar It creates a toolbar, which is a bar across the top of
the figure containing quick-access buttons.
Toolbar uipushtool It creates a pushbutton to go in a toolbar.
Toolbar uitoggletool It creates a toggle button to go in a toolbar.
Toggle
Axes axes It creates a new set of axes to display data on. Axes
never trigger callbacks.
Figure 5.1 : Figure Window showing examples of MATLAB GUI elements. From top to
bottom and left to right, the elements are: (1) a pushbutton; (2) a toggle button in the
‘on’ state;(3) two radio buttons within a button group; (4) a check box; (5) a label and an
edit box; (6) a slider; (7) a set of axes; and (8) a list box.
5.2 CREATING AND DISPLAYING A GRAPHICAL USER INTERFACE
 MATLAB Graphical User Interfaces are created using a tool called guide, the GUI
Development Environment.
 This tool allows a programmer to lay out the GUI, selecting and aligning the GUI
components to be placed in it.
 Once the components are in place, the programmer can edit their properties:
name, color, size, font, text to be displayed, and so on.
 When guide saves the GUI, it creates a working program, including skeleton
functions that the programmer can modify to implement the behavior of the GUI.
 When guide is executed, it creates the Layout Editor, shown in Figure 5.2.

Figure 5.2: The guide tool window


 The large gray area with grid lines is the layout area, where a programmer can lay
out the GUI.
 The Layout Editor window has a palate of GUI components along the left-hand
side of the layout area.
 A user can create any number of GUI components by first clicking on the desired
component and then dragging its outline in the layout area.
 The top of the window has a toolbar with a series of useful tools that allow the
user to distribute and align GUI components, modify the properties of GUI
components, and add menus to GUIs, among other things.
 The basic steps required to create a MATLAB GUI as follows:
1. Decide what elements are required for the GUI and what the function of each
element will be. Make a rough layout of the components by hand on a piece of
paper.
2. Use the MATLAB tool called guide (GUI Development Environment) to lay out the
components on a figure. The size of the figure and the alignment and spacing of
components on the figure can be adjusted using the tools built into guide.
3. Use a MATLAB tool called the Property Inspector (built into guide) to give each
component a name (a “tag”) and to set the characteristics of each component,
such as its color or the text it displays.
4. Save the figure to a file. When the figure is saved, two files will be created on disk
with the same name but different extents.
i. The fig file contains the GUI layout and the components of the GUI
ii. The M-file contains the code to load the figure as well as skeleton callback
functions for each GUI element.
5. Write code to implement the behavior associated with each callback function.
Example:
 Let us consider a simple GUI that contains a single pushbutton and a single text
string. Each time the pushbutton is clicked, the text string will be updated to
show the total number of clicks since the GUI started.
Step 1: The design of this GUI is very simple. It contains a single pushbutton and a
single text field. The callback from the pushbutton will cause the number displayed in
the text field to increase by one each time the button is pressed. A rough sketch of the
GUI is shown in Figure 5.3.

Figure 5.3: Rough layout for a GUI containing a single pushbutton and a single
label field

Step 2: To lay out the components on the GUI, run the MATLAB function guide. When
guide is executed, it creates the window shown in Figure 10.2. First, we must set the
size of the layout area, which will become the size of the final GUI. We do this by dragging
the small square on the lower-right corner of the layout area until it has the desired size
and shape. Then, click on the “pushbutton” button in the list of GUI components and
create the shape of the pushbutton in the layout area. Finally, click on the “text” button
in the list of GUI components and create the shape of the text field in the layout area.
The resulting figure after performing these steps is shown in Figure 5.4. We could now
adjust the alignment of these
two elements using the
Alignment Tool, if desired.
Step 3: To set the properties
of the pushbutton, click on
the button in the layout area
and then select “Property
Inspector” ( ) from the
toolbar. Alternatively, right-
click on the button and
select “Property Inspector”
from the popup menu. The
Property Inspector window
shown in Figure 5.5 will
appear. Note that this
window lists every property
available for the pushbutton
and allows us to set each Figure 5.4: The completed GUI layout within the guide
value using a GUI interface. window.

Figure 5.5: The Property Inspector showing the properties of the pushbutton. Note that
the String is set to 'Click Here', and the Tag is set to 'MyFirstButton'.

The Property Inspector performs the same function as the get and set functions.
For the pushbutton, we may set many properties such as color, size, font,
text and alignment. However, we must set two properties: the String property, which
contains the text to be displayed, and the Tag property, which is the name of the
pushbutton. In this case, the String property will be set to'Click Here', and the Tag
property will be set to MyFirstButton. For the text field, we must set two properties: the
String property, which contains the text to be displayed, and the Tag property, which is
the name of the text field. This name will be needed by the callback function to locate
and update the text field. In this case, the String property will be set to 'Total Clicks: 0',
and the Tag property defaults to 'MyFirstText'. The layout area after performing these
steps is shown in Figure 5.6.

Figure 5.6 :The design area after the properties of the pushbutton and the text
field have been modified.
It is possible to set the properties of the figure itself by clicking on a clear spot in
the Layout Editor and using the Property Inspector to examine and set the figure’s
properties. Although not required, it is a good idea to set the figure’s Name property.
The string in the Name property will be displayed in the title bar of the resulting GUI
when it is executed. In this program, we will set the Name to 'MyFirstGUI'.
Step 4: We will now save the layout area under the name MyFirstGUI. Select the
“File/Save As” menu item, type the name MyFirstGUI as the file name, and click “Save”.
This action will automatically create two files: MyFirstGUI.fig and MyFirstGUI.m. The
figure file contains the actual GUI that we have created. The M-file contains code that
loads the figure file and creates the GUI, plus a skeleton callback function for each
active GUI component. At this point, we have a complete GUI, but one that does not yet
do the job it was designed to do. You can start this GUI by typing MyFirstGUI in the
Command Window, as shown in Figure 5.7. If the button is clicked on this GUI, nothing
happens.

Figure 5.7: Typing MyFirstGUI in the Command Window starts the GUI.
 A portion of the M-file automatically created by guide is shown in Figure 10.8.
This file contains the main function MyFirstGUI, plus subfunctions to specify the
behavior of the active GUI components. The file contains a dummy callback
function for every active GUI component that you defined. In this case, the only
active GUI component was the pushbutton, so there is a callback function called
MyFirstButton_Callback, which is executed when the user clicks on the button.
function varargout = MyFirstGUI(varargin)
% MYFIRSTGUI M-file for MyFirstGUI.fig
% MYFIRSTGUI, by itself, creates a new MYFIRSTGUI or raises the existing
% singleton*.
%
% H = MYFIRSTGUI returns the handle to a new MYFIRSTGUI or the handle to
% the existing singleton*.
%
% MYFIRSTGUI('CALLBACK',hObject,eventData,handles,...) calls the local
% function named CALLBACK in MYFIRSTGUI.M with the given input arguments.
%
% MYFIRSTGUI('Property','Value',...) creates a new MYFIRSTGUI or raises the
% existing singleton*. Starting from the left, property value pairs are
% applied to the GUI before MyFirstGUI_OpeningFunction gets called. An
% unrecognized property name or invalid value makes property application
% stop. All inputs are passed to MyFirstGUI_OpeningFcn via varargin.
%
% *See GUI Options on GUIDE's Tools menu. Choose "GUI allows only one
% instance to run (singleton)".
%
% See also: GUIDE, GUIDATA, GUIHANDLES
% Edit the above text to modify the response to help MyFirstGUI
% Last Modified by GUIDE v2.5 21-Feb-2004 16:17:45
% Begin initialization code - DO NOT EDIT
gui_Singleton = 1;
gui_State = struct('gui_Name', mfilename, ...
'gui_Singleton', gui_Singleton, ...
'gui_OpeningFcn', @MyFirstGUI_OpeningFcn, ...
'gui_OutputFcn', @MyFirstGUI_OutputFcn, ...
'gui_LayoutFcn', [] , ...
'gui_Callback', []);
if nargin & isstr(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 MyFirstGUI is made visible.
function MyFirstGUI_OpeningFcn(hObject, eventdata, handles, varargin)
% This function has no output args, see OutputFcn.
% hObject handle to figure
% eventdata reserved - to be defined in a future version of MATLAB
% handles structure with handles and user data (see GUIDATA)
% varargin command line arguments to MyFirstGUI (see VARARGIN)
% Choose default command line output for MyFirstGUI
handles.output = hObject;
% Update handles structure
guidata(hObject, handles);
% UIWAIT makes MyFirstGUI wait for user response (see UIRESUME)
% uiwait(handles.figure1);
% --- Outputs from this function are returned to the command line.
function varargout = MyFirstGUI_OutputFcn(hObject, eventdata, handles)
% varargout cell array for returning output args (see VARARGOUT);
% hObject handle to figure
% eventdata reserved - to be defined in a future version of MATLAB
% handles structure with handles and user data (see GUIDATA)
% Get default command line output from handles structure
varargout{1} = handles.output;
% --- Executes on button press in MyFirstButton.
function MyFirstButton_Callback(hObject, eventdata, handles)
% hObject handle to MyFirstButton (see GCBO)
% eventdata reserved - to be defined in a future version of MATLAB
% handles structure with handles and user data (see GUIDATA)

Figure 5.8: The M-file for MyFirstGUI, automatically created by guide.

 If function MyFirstGUI is called without arguments, then the function displays the
GUI contained in file MyFirstGUI.fig. If function MyFirstGUI is called with
arguments, then the function assumes that the first argument is the name of a
subfunction, and it calls that subfunction using feval, passing the other
arguments on to that subfunction.
 Each callback function handles events from a single GUI component. If a mouse
click (or keyboard input for edit fields) occurs on the GUI component, then the
component’s callback function will be automatically called by MATLAB.
 The name of the callback function will be the value in the Tag property of the GUI
component plus the characters “_Callback”. Thus, the callback function for
MyFirstButton will be named MyFirstButton_Callback. M-files created by guide
contain callbacks for each active GUI component, but these callbacks don’t do
anything yet.
Step 5: Now, we need to write the callback subfunction code for the pushbutton. This
function will include a persistent variable that can be used to count the number of clicks
that have occurred.
 When a click occurs on the pushbutton, MATLAB will call the function
MyFirstGUI with MyFirstButton_Callback as the first argument. Then function
MyFirstGUI will call subfunction MyFirstButton_Callback, as shown in Figure
5.9.
 This function should increase the count of clicks by one, create a new text string
containing the count, and store the new string in the String property of the text
field MyFirstText. A function to perform this step is shown here:
function MyFirstButton_Callback(hObject, eventdata, handles)
% hObject handle to MyFirstButton (see GCBO)
% eventdata reserved - to be defined in a future version of MATLAB
% handles structure with handles and user data (see GUIDATA)
% Declare and initialize variable to store the count
persistent count
if isempty(count)
count = 0;
end
% Update count
count = count + 1;
% Create new string
str = sprintf('Total Clicks: %d',count);
% Update the text field
set (handles.MyFirstText,'String',str);

Figure 10.9: Event handling in program MyFirstGUI. When a user clicks on the button with
the mouse, the function MyFirstGUI is called automatically with the argument
MyFirstButton_Callback. Function MyFirstGUI in turn calls subfunction
MyFirstButton_Callback. This function increments count, and then saves the new count in the
on text field the GUI.
 This function declares a persistent variable count and initializes it to zero. Each
time the function is called, it increments count by 1 and creates a new string
containing the count. Then, it updates the string displayed in the text field
MyFirstText.
 The resulting program is executed by typing MyFirstGUI in the Command
Window. When the user clicks on the button, MATLAB automatically calls
function MyFirstGUI with MyFirstButton_Callback as the first argument, and
function MyFirstGUI calls subfunction MyFirstButton_Callback.
 This function increments variable count by one and updates the value displayed
in the text field.
 The GUI that result after three button pushes is shown in Figure 5.10.

Figure 5.10: The resulting program after three button pushes.

Some other Description of the function MyFirstGUI


 Figure 10.8 shows the M-file that was automatically generated by guide
forcMyFirstGUI.
 This function cuses varargin to represent its input arguments and varargout to
represent its coutput results.
 function varargin can represent can arbitrary number of input arguments, and
function varargout can represent acvarying number of output arguments.
Therefore, a user can call function MyFirstGUI with any number of arguments.
 The main function creates a structure called gui_State. The code to create this
structure is

gui_Singleton = 1;
gui_State = struct('gui_Name', mfilename, ...
'gui_Singleton', gui_Singleton, ...
'gui_OpeningFcn', @MyFirstGUI_OpeningFcn,
...
'gui_OutputFcn', @MyFirstGUI_OutputFcn, ...
'gui_LayoutFcn', [] , ...
'gui_Callback', []);
if nargin & isstr(varargin{1})
gui_State.gui_Callback = str2func(varargin{1});
end
 The structure contains some control information, plus function handles for some
of the subfunctions in the file.
 Other MATLAB GUI functions use these function handles to call the subfunctions
from outside of the M-file.The first argument is converted into a callback function
handle, if it exists.
 The value gui_Singleton specifies whether there can be one or more simultaneous
copies of the GUI. If gui_Singleton is 1, then there can be only one copy of the
GUI. If gui_Singleton is 0, then there can be many simultaneous copies of the
GUI.
 The main function calls the MATLAB function gui_mainfcn and passes the
gui_State structure and all of the input arguments to it.
 Function gui_mainfcn is a standard MATLAB function. It actually does the work
of creating the GUI, or of calling the appropriate subfunction in response to a
callback.
Calling the M-File without Arguments:
 If the user calls MyFirstGUI without arguments, function gui_mainfcn loads the
GUI from the figure file MyFirstGUI.fig using the openfig function. The form of this
function is
fig = openfig(mfilename,reuse);
 Where mfilename is the name of the figure file to load. The second argument in
the function specifies whether there can be only one copy of the figure running at
a given time or multiple copies can be run.
 If gui_State.gui_ Singleton is 1, then the second argument is set to 'reuse', and
only one copy of the figure can be run.
 If openfig is called with the 'reuse' option and the specified figure already exists,
the preexisting figure will be brought to the top of the screen and reused.
 In contrast, if gui_State.gui_Singleton is 0, then the argument is set to 'new', and
a new copy of the figure will be created each time MyFirstGUI is called without
arguments.
 By default, a GUI created by guide has the gui_State.gui_Singleton set to 1, so
only one copy of the figure can exist at any time.
 If you wish to have multiple copies of the GUI, turn off the “GUI allows only one
instance to run” flag in the GUI Options selection on guide’s Tools menu.
 After the figure has been loaded, the gui_mainfcn function executes the statement
set(fig,'Color',get(0,'defaultUicontrolBackgroundColor'));
 This function sets the background color of the figure to match the default
background color used by the computer that MATLAB is executing on.
 It makes the color of the GUI match the color of native windows on the computer.
Therefore,
 a GUI can be written on a Windows-based PC and used on a Unix-based
computer, and vice versa. It will look natural in either environment.
 Function gui_mainfcn creates a structure containing the handles of all the objects
in the current figure, and stores that structure as application data in the figure.
guidata(gui_hFigure, guihandles(gui_hFigure));
 Function guihandles creates a structure containing handles to all of the objects
within the specified figure.
 The element names in the structure correspond to the Tag properties of each GUI
component, and the values are the handles of each component.
 For example, the handle structure returned in MyFirstGUI.m is
>> handles = guihandles(fig)
handles =
figure1: 99.0005
MyFirstText: 3.0021
MyFirstButton: 100.0007
 There are three GUI components in this figure—the figure itself, plus a text field
and a pushbutton. Function guidata saves the handles structure as application
data in the figure, using the setappdata function.
 Before making the figure visible, function gui_mainfcn calls the function specified
in gui_OpeningFcn.
 This function provides a way for the programmer to customize the GUI before
showing it to the user.
 For example, a programmer could load initial data values here, change
background colors, and so forth.
Calling the M-File with Arguments:
 When the user clicks on an active GUI element, MATLAB calls MyFirstGUI with
the name of the GUI element’s callback function in the first argument.
 If MyFirstGUI is called with arguments, the value returned by nargin will be
greater than zero.
 In this case, function MyFirstGUI converts the callback function name into a
function handle using the following code.

if nargin & isstr(varargin{1})


gui_State.gui_Callback = str2func(varargin{1});
end

 When function gui_mainfcn is called this time, it calls the callback function
 using this function handle. The callback executes and responds to the mouse
click or keyboard input, as appropriate.
 Figure 5.11 summarizes the operation of MyFirstGUI on first and subsequent
calls.

Figure 5.11 The operation of MyFirstGUI. If there are no calling arguments, it either
creates a GUI or displays an existing GUI. If there are calling arguments, the first
arguments is assumed to be a callback function name, and MyFirstGUI calls the
appropriate callback function.
The Structure of a Callback Subfunction:
 Every callback subfunction has the standard form
function ComponentTag_Callback(hObject, eventdata, handles)
 where ComponentTag is the name of the component generating the callback
(the string in its Tag property). The arguments of this subfunction are as follows:
 hObject—The handle of the parent figure.
 eventdata—A currently unused (in MATLAB 7) array.
 Handles—The handles structure contains the handles of all GUI
components on the figure.
 Each callback function has full access to the handles structure, and so each
callback function can modify any GUI component in the figure. We took advantage
of this structure in the callback function for the pushbutton in MyFirstGUI, where
the callback function for the pushbutton modified the text displayed in the text
field.
 % Update the text field
set (handles.MyFirstText,'String',str);
GRAPHICAL USER INTERFACE COMPONENTS
• It describes how to create and use each component, as well as the types of events
each component can generate.
• The components are
1. Static Text Fields
2. Edit Boxes
3. Pushbuttons
4. Toggle Buttons
5. Checkboxes
6. Radio Buttons
7. Popup Menus
8. List Boxes
9. Sliders
1. Static Text Fields:
 A static text field is a graphical object that displays one or more text strings, which
are specified in the text field’s String property.
 The String property accepts a string or a cell array of strings.
 If the input value is a string, it will be displayed on a single line.
 If the input value is a cell array of strings, the first element will be displayed on
the first line of the text box, the second element will be displayed on the second
line of the text box, and so on.
 You can specify the text alignment in the display area by setting the horizontal
alignment property.
 By default, text fields are horizontally centered.
 A text field is created by a uicontrol whose style property is 'text'.
 A text field may be added to a GUI by using the text tool ( ) in the Layout Editor.
 Text fields do not create callbacks, but the value displayed in the text field can be
updated from another component’s callback function by changing the text field’s
String property.
2. Edit Boxes
 An edit box is a graphical object that allows a user to enter one or more text
strings.
 It is created by a uicontrol whose style property is 'edit'.
 If the min property and max property are both set to 1, then the edit box will
accept a single line of text, and it will generate a callback when the user presses
the Enter key or the ESC key after typing the text.
 Figure 10.12a shows a simple GUI containing an edit box named 'EditBox' and a
text field named 'TextBox'.
 When a user presses Enter or ESC after typing a string into the edit box, the
program automatically calls the function EditBox_Callback, which is shown in
Figure 10.12b

Figure 10.12a

function EditBox_Callback(hObject, eventdata, handles)


str = get (handles.EditBox,'Strhandles)
set (handles.TextBox,'String',str);

Figure 10.12b
 This function locates the edit box using the handles structure, and recovers the
string typed by the user. Then, it locates the text field and displays the string in
the text field.
 Figure 10.13 shows this GUI just after it has started, and after the user has typed
the word “Hello” in the edit box.

Figure 10.13 (a) The GUI produced by program test_edit. (b) The GUI after a user types
'Hello'into the edit box and presses Enter.
3. Pushbuttons
 A pushbutton is a component that a user can click on to trigger a specific action.
 The pushbutton generates a callback when the user clicks on it with the mouse.
 A pushbutton is created by creating a uicontrol whose style property is
'pushbutton'. It can be added to a GUI by using the pushbutton tool( ) in the
Layout Editor.
4. Toggle Buttons
 A toggle button is a type of button that has two states: on (depressed) and off (not
depressed).
 A toggle button switches between these two states whenever the mouse clicks on
it, and it generates a callback each time.
 The 'Value' property of the toggle button is set to max (usually 1) when the button
is on, and min (usually 0) when the button is off.
 A toggle button is created by a uicontrol whose style property is 'togglebutton'.
 It can be added to a GUI by using the toggle button tool ( ) in the Layout Editor.
5. Checkboxes and Radio Buttons
 Checkboxes and radio buttons are essentially identical to toggle buttons except
that they have different shapes.
 They have two states: on and off.
 They switch between these two states whenever the mouse clicks on them,
generating a callback each time.
 The 'Value' property of the checkbox or radio button is set to max (usually 1) when
it is on, and min (usually 0) when it is off.
 A checkbox is created by a uicontrol whose style property is 'checkbox', and a
radio button is created by a uicontrol whose style property is 'radiobutton'.
 A checkbox may be added to a GUI by using the checkbox tool
 ( ) in the Layout Editor, and a radio button may be added to a GUI by using the
radio button tool ( ) in the Layout Editor.
 Checkboxes are traditionally used to display on/off options.
 Groups of radio buttons are traditionally used to select among mutually exclusive
options.
6. Popup Menus
 Popup menus are graphical objects that allow a user to select one of a mutually
exclusive list of options.
 The list of options that the user can select among is specified by a cell array of
strings, and the 'Value' property indicates which of the strings is currently
selected.
 A popup menu may be added to a GUI by using the popup menu tool in the Layout
Editor.
 Figure 10.22a shows an example of a popup menu.
 This GUI in this figure creates a popup menu with five options, labeled “Option
1,” “Option 2,” and so forth.

7. List Boxes
 List boxes are graphical objects that display many lines of text and allow a user
to select one or more of those lines.
 If there are more lines of text than can fit in the list box, a scroll bar will be created
to allow the user to scroll up and down within the list box.
 The lines of text that the user can select among are specified by a cell array of
strings, and the 'Value' property indicates which of the strings are currently
selected.
 A list box is created by a uicontrol whose style property is 'listbox'.
 A list box may be added to a GUI by using the listbox tool ( ) in the Layout
Editor.
 Figure 10.24a shows an example of a single-selection list box.
 The GUI in this figure creates a list box with eight options, labeled “Option 1,”
“Option 2,” and so forth.
 It creates a pushbutton to perform selection and a text field to display the selected
choice.
 Both the list box and the pushbutton generate callbacks.

8. Sliders
 Sliders are graphical objects that allow a user to select values from a continuous
range between a specified minimum value and a specified maximum value by
moving a bar with a mouse.
 The 'Value' property of the slider is set to a value between min and max
depending on the position of the slider.
 A slider is created by a uicontrol whose style property is 'slider'.
 A slider may be added to a GUI by using the slider tool ( ) in the Layout Editor.

DIALOG BOXES:
 A dialog box is a special type of figure that is used to display information or to get
input from a user.
 Dialog boxes are used to display errors, provide warnings, ask questions, or get
user input.
 They are also used to select files or printer properties.
 Dialog boxes may be modal or non-modal.
 A modal dialog box does not allow any other window in the application to be
accessed until it is dismissed, while a normal dialog box does not block access to
other windows.
 Modal dialog boxes are typically used for warning and error messages that need
urgent attention and cannot be ignored.
 By default, most dialog boxes are non-modal.
 MATLAB includes many types of dialog boxes, the more important of which are
summarized in Table 10.5.

 There are 4 different Dialog Boxes. These are
1. Error and Warning Dialog Boxes
2. Input Dialog Boxes
3. The uigetfile, uisetfile, and uigetdir Dialog Boxes
4. The uisetcolor and uisetfont Dialog Boxes
1. Error and Warning Dialog Boxes:
 Error and warning dialog boxes have similar calling parameters and behavior.
 The only difference between them is the icon displayed in the dialog box.
 The most common calling sequence for these dialog boxes is
errordlg(error_string,box_title,create_mode);
warndlg(warning_string,box_title,create_mode);
 The error_string or warning_string is the message to display to the user, and the
box_title is the title of the dialog box.
 create_mode is a string that can be 'modal' or 'non-modal', depending on the type
of dialog box you wish to create.
 The following statement creates a modal error message that cannot be ignored by
the user.
errordlg('Invalid input values!','Error Dialog Box','modal');
 The dialog box produced by this statement is shown in Figure.

An error dialog box


2. Input Dialog Boxes
 Input dialog boxes prompt a user to enter one or more values that may be used
by a program.
 They may be created with one of the following calling sequences:
o answer = inputdlg(prompt)
o answer = inputdlg(prompt,title)
o answer = inputdlg(prompt,title,line_no)
o answer = inputdlg(prompt,title,line_no,default_answer)
 prompt is a cell array of strings, with each element of the array corresponding to
one value that the user will be asked to enter.
 The parameter title specifies the title of the dialog box,
 while line_no specifies the number of lines to be allowed for each answer.
 default_answer is a cell array containing the default answers that will be used if
the user fails to enter data for a particular item.
 There must be as many default answers as there are prompts.
 When the user clicks the OK button on the dialog box, his or her answers will be
returned as a cell array of strings in variable answer.
Example of an input dialog box
 Suppose that we wanted to allow a user to specify the position of a figure using
an input dialog.
 The code to perform this function would be

prompt{1} = 'Starting x position:';
prompt{2} = 'Starting y position:';
prompt{3} = 'Width:';
prompt{4} = 'Height:';
title = 'Set Figure Position';
default_ans = {'50','50','180','100'};
answer = inputdlg(prompt,title,1,default_ans);

 The resulting dialog box is shown in Figure 10.34.

Figure 10.34 An input dialog box.

3. The uigetfile, uisetfile, and uigetdir Dialog Boxes


 The uigetfile and uisetfile dialog boxes allow a user to interactively pick files to
open or save.
 These functions use the standard file open or file save dialog boxes for the
particular operating system that MATLAB is running on.
 They return strings containing the name and the path of the file but do not
actually read or save it.
 The programmer is responsible for writing additional code for that purpose of read
or save of the file.
 The form of these two dialog boxes is
[filename, pathname] = uigetfile(filter_spec,title);
[filename, pathname] = uisetfile(filter_spec,title);
 Parameter filter_spec is a string specifying the type of files to display in the dialog
box, such as '*.m', '*.mat', and so on.
 Parameter title is a string specifying the title of the dialog box. After the dialog box
executes, filename contains the name of the selected file and pathname contains
the path of the file.
 If the user cancels the dialog box, filename and pathname are set to zero.
 The following script file illustrates the use of these dialog boxes.

[filename, pathname] = uigetfile('*.mat','Load MAT File');


if filename ~= 0
load([pathname filename]);
end

 It prompts the user to enter the name of a Mat-file, and then reads the contents
of that file.
 The dialog box created by following code on a Windows 2000 Professional system
is shown in Figure 10.35.

Figure 10.35 A file open dialog box created by uigetfile.


 The uigetdir dialog box allows a user to interactively select a directory.
 This function uses the standard directory selection dialog box for the particular
operating system that MATLAB is running on.
 It returns the name of the directory but does not actually do anything with it.
 The programmer is responsible for writing additional code to use the directory
name.
 The form of this dialog box is
directoryname = uigetdir(start_path, title);
 Parameter start_path is the path of the initially selected directory. If it is not
valid, the dialog box opens with the base directory selected.
 Parameter title is a string specifying the title of the dialog box. After the dialog
box executes, directoryname contains the name of the selected directory.
 If the user cancels the dialog box, directoryname is set to zero.
 The following script file illustrates the use of this dialog box.

dir1 = uigetdir('d:\matlab7\work','Select a directory');


if dir1 ~= 0
cd(dir1);
end

 It prompts the user to select a directory starting with the current MATLAB working
directory.
 This dialog box created by this code on a Windows 2000 Professional system is
shown in Figure 10.36.

4. The uisetcolor and uisetfont Dialog Boxes


 The uisetcolor and uisetfont dialog boxes allow a user to interactively select colors
or fonts using the standard dialog boxes for the computer on which MATLAB is
executing.
 The appearances of these boxes will vary for different operating systems. They
provide a standard way to select colors or fonts within a MATLAB GUI.

You might also like