UNIT-5 MATLAB
UNIT-5 MATLAB
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.
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
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.
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
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 (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)
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)
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.
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.
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
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.
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.
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.