Anda di halaman 1dari 27

1

Introduction
In this lecture we shall continue to use MATLAB programming to solve some applied
dynamics problems. A summary of some fundamental MATLAB features follow next.
An introduction to Matlab may be found at
Tutorials
Take a look at these flash videos in your own time.
MATLAB Programming
This section describes some of the basic features of MATLAB programming. For a more
detailed study of MATLAB, the reader is referred to the MATLAB help files (invoked by
pressing the F1 key or typing help at the MATLAB command) or any introductory book on
MATLAB programming for engineers and scientists.
MATLAB is a high-level language for technical computing. It integrates computation,
visualization, and programming in an environment where problems and solutions are
expressed in mathematical notation. Typical application areas include:
- Mathematical and computational algorithm development
- Numerical modelling and simulation
- Data analysis and visualisation
- Scientific and engineering graphics
- Application development, including graphical user interface building
- Data acquisition and control in real time

MATLAB stands for Matrix Laboratory; hence, the basic storage unit for any MATLAB
variable is the matrix also known as an array.
Command Line
MATLAB (like the old DOS or UNIX terminal) is a command-line system. When you open
MATLAB for the first time, you see the Command Window with the command line prompt
>> and flashing cursor position. Individual MATLAB commands may be typed at the
command line prompt. Or multiple commands may be written if they are separated by
commas or semi-colons.
Workspace
The Workspace window should be visible in the MATLAB window (if not, go to
Desktop/workspace in the command list at the top).
The workspace is the repository for any MATLAB constants or named variables that the user
creates during the course of a MATLAB session. For example, to create a variable, lets call
it x, and give it a value of 5 type:
x=5

2

at the command line. MATLAB echoes the details of the variable just created. Take a look in
the workspace window and you will see a new variable with the name x and a value of 5.
Because we are working in the Matrix Laboratory, x is a 1x1 dimensions array.
To stop the automatic echo, use a semi-colon. Type
y=9;
and see what happens.
To create larger arrays or matrices we use square brackets, commas (or spaces will do) and
semi-colons. The square brackets indicate that the values are to be stored in an array.
Commas or spaces are used to distinguish individual entries along the rows. Semi-colons are
used to distinguish a new row. Typing
A = [1 2 ; 3 4];
at the command line will create a 2x2 array in the workspace.
We can transpose a matrix (flip it about its diagonal) by using the apostrophe. Create a new
array B which is the transpose of A by typing.
B=A'
The transpose function is useful for turning a row array into a column array and vice versa.
Try
C = [1 2 3 4 5 6]

3

D = [1 2 3 4 5 6]
E = [1;2;3]
F = [1;2;3]
Note that we can use the = command to relate variable; hence, D=C and F=E would have
worked too.
Note that the command = is used to assign a value to a parameter. It does not mean equal
to more later.
To find out what variables are in the workspace at any time type the command who at the
command prompt. The workspace can be saved and retrieved for later use. The command
clear is useful for removing all variables from the workspace.
MATLAB Path
When you open MATLAB you see a window called current directory. This current
directory has a location on the hard drive as C:\MATLAB7\work (depending on the version
of MATLAB installed). The current directory is always \work by default. You can
change the working directory at any other location. MATLAB files in the current directory
are always visible to MATLAB. If MATLAB files are stored outside of the current directory
then they must be in file locations that are designated on the MATLAB path. Otherwise,
MATLAB will not be able to run these files. To see the path type path at the command
prompt or go to file\set path on the command list at the top. By taking the latter approach,
one can add or remove file locations to the MATLAB path.
Command History
The other window usually visible on the MATLAB window is called Command History. This
window stores the list of previous MATLAB commands from the current session and
previous sessions. The up and down arrow keys ( and ) may be used at the command
prompt to toggle through previous commands.

MATLAB Files
Files that contain code in the MATLAB language are called M-files. You create M-files
using a text editor, then use them as you would any other MATLAB function or command.
There are two kinds of M-files:
1. Scripts, which do not accept input arguments or return output arguments. They
operate on data in the workspace.
2. Functions, which can accept input arguments and return output arguments. Internal
variables are local to the function.
If you're a new MATLAB program, just create the M-files that you want to try out in the
current directory. As you develop more of your own M-files, you will want to organize them
into other directories and personal toolboxes that you can add to your MATLAB path. If you
duplicate function or script file names, MATLAB executes the one that occurs first in the
search path.

4

MATLAB script files
Scripts files (or batch files) are lists of commands that are operated in a sequence. The
sequence or flow is controlled by the code, but the default sequence is to complete each
command one at a time... more on this topic later.
Last week we wrote a few of our own script files to solve for axle loads. An important point
about file name, they should be a single string of characters (no spaces allowed) followed by
the extension .m. To run the script file you can use the MATLAB editor/debug commands
or type the file name without the .m extension at the MATLAB command line prompt.
You may call a script file command from within another script file.
MATLAB Function files
Functions are M-files that can accept input arguments and return output arguments. The
names of the M-file and of the function should be the same. Functions operate on variables
within their own workspace, separate from the workspace you access at the MATLAB
command prompt. A good example is provided by the command rank. The M-file rank.m is
available in the directory toolbox/matlab/matfun
You can see a file with the command type followed by the filename.
In our case insert type rank
Here is the file as written in MATLAB.
function r = rank(A,tol)
% RANK Matrix rank.
% RANK(A) provides an estimate of the number of linearly
% independent rows or columns of a matrix A.
% RANK(A,tol) is the number of singular values of A
% that are larger than tol.
% RANK(A) uses the default tol = max(size(A)) * norm(A) * eps.

s = svd(A);
if nargin==1
tol = max(size(A)') * max(s) * eps;
end
r = sum(s > tol);

The first line of a function M-file starts with the keyword function. It gives the function name
and order of arguments. In this case, there are up to two input arguments and one output

5

argument. The next several lines, up to the first blank or executable line, are comment lines
that provide the help text. These lines are printed when you type help rank
The rest of the file is the executable MATLAB code defining the function. The variable s
introduced in the body of the function, as well as the variables on the first line, r, A and tol,
are all local to the function; they are separate from any variables in the MATLAB workspace.
This example illustrates one aspect of MATLAB functions that is not ordinarily found in
other programming languages -- a variable number of arguments. The rank function can be
used in several different ways. rank(A)
r = rank(A)
r = rank(A,1.e-6)
Many M-files work this way. If no output argument is supplied, the result is stored in the
default variable ans. If the second input argument is not supplied, the function computes a
default value.

Flow Control
Using programming statements we can control the flow or sequence of commands in
MATLAB.
The most widely used conditional flow statement is the if structure.

The first of these to look at is the if-end structure
It can be written in code seen in figure 1 below. The figure shows how the commands are
types into the program, and the flowchart symbolically shows the flow. Or the sequence, in
which the commands are executed. As the program executes, it reached the if statement.
If the conditional expression is true (1), the program continues to execute the commands that
follow the if statement all the way down to the end statement.
If the conditional expression is false (0), the program skips the commands that follow the if
statement all the way down to the end statement, and continues with the commands that
So, if we had the following problem of calculating a workers pay. Lets say that a worker is
paid according to his hourly wage up to 40 hours, and 50% more for over time above the 40
hours. Write a program in a script file that calculates the pay to a worker. The program has to
ask the user to enter the number of hours and the hourly wage. The program is then to display
the pay.

6

If
Statement
Commands
True
False
Flowchart
End
..
.. MATLAB program
.
if conditional expression
..
..
..
end
..
.. MATLAB program
.

Figure 1: the structure of the if-else conditional statement

%Script file: pay.m
%
%Purpose
% This program calculates the pay of a worker for a given number of
% hours. If the number of hours is over 40 hours, then a weighting of
% 50% extra is given on base salary for the extra hours
%
%Record of revisions:
% Date Programmer Description of Change
% ==== ========== =====================
% 25/12/20212 Gerard Nagle Original code
%
%Define Variables:
% t -Number of hours Worked
% h -Hourly wage
% Pay -Calculated Pay

t=input('Please enter the number of hours worked ');
h=input('please enter the hourly wage in ');
Pay=t*h;
if t>40
Pay=Pay+(t-40)*0.5*h;
end
fprintf('The workers pay is \$%5.2f', Pay)

7

Note on fprintf
The fprintf can be used to display output (text and data) on to the MATLAB command
window or save it to a file. This command allows the output to be formatted. Also text and
data can be intermixed and displayed on the same line.
fprintf(text as string %-5.2f additional text, variable name)
The % sign marks the
spot where the number
is inserted within the text
Formatting elements.
(These define the format
of the number)
The name of the
variable whose value is
displayed

And the formatting elements are;
-5.2f
Flag
(optional)
Field width and precision
(optional)
Conversion character
(required!)

Where the flag is;
- (minus sign) Left justify within the field
+ (plus sign) Prints a character (+ or -) in front of the number)
0 (zero) adds zeros if the number is shorter than the field.
Conversion character
E or e is exponential using upper or lower case
f is fixed point notation
i is integer

8

if-else-end
The if statement evaluates a logical expression and executes a group of statements when the
expression is true. The first line if an if statement with a conditional expression. If the
conditional expression is true (1), the program
If
Statement
Commands
Group 1
True
False
Flowchart
End
..
.. MATLAB program
.
if conditional expression
..
..
..
else
..
..
..
end
..
..MATLAB program
Commands
Group 2
Group 2 of
MATLAB commands
Group 1 of
MATLAB commands

A water tank has the geometer as shown in the figure below. The lower part is a cylinder, and
the upper part is an inverted frustum cone. There is a float in the tank that indicates the level
of the water. We have to write a function that determines the volume of the water in the tank
from the height of the water in the tank.

Diameter 25 m
19 m
14 m
Diameter 46 m
rh
h

9

%Function file: watervol.m
%
%Purpose
% This programme calculates the volume of water in a water tower.
% The dimensions of the tower are as in that attached diagram.
%
%
%Record of revisions:
% Date Programmer Description of Change
% ==== ========== =====================
% 25/12/2012 Gerard Nagle Original code
%
%Define Variables:
% h -Height of Water in tower
% rh -radius of upper inverted frustum cone

function v = watervol(h)
if h<=19
v=pi*12.5^2*h;
else
rh=12.5+10.5*(h-19)/14;
v=pi*12.5^2*19+pi*(h-19)*(12.5^2+12.5*rh+rh^2)/3;
end

if-elseif-else-end
The if statement evaluates a logical expression and executes a group of statements when the
expression is true. The optional elseif and else keywords provide for the execution of
alternate groups of statements. An end keyword, which matches the if, is required to denote
the end of the statements. The groups of statements are delineated by the four keywords -- no
braces or brackets are involved. The typical command structure is:

As an example, we will consider the solution of a quadratic equation that we all have seen. It
can be
2
0 ax bx c + + =
The solution to this is
2
4
2
b b ac
x
a

=
The term
2
4 b ac is known as the discriminant of the equation. This can have three options.
If
2
4 0 b ac > , then there are two distinct and real roots. If
2
4 0 b ac = , then there is a
single repeated root to the equation. If
2
4 0 b ac < , then there are two complex roots.

10

If
Statement
Commands
Group 1
True
False
Flowchart
End
Commands
Group 2
Commands
Group 3
elseif
Statement
True
False
..
.. MATLAB program
.
if conditional expression
..
..
..
elseif
..
..
..
else
..
..
..
end
..
..MATLAB program
Group 2 of
MATLAB commands
Group 1 of
MATLAB commands
Group 3 of
MATLAB commands

%Script file: calc_roots.m

%Script file: calc_roots.m
%
%Purpose
% This program solves for the roots of a quadratic equation of the form
% a*x**2 + b*x + c = 0. It calculates the answers regardless if the type
% of roots that the equation possesses
% %
%
%Record of revisions:
% Date Programmer Description of Change
% ==== ========== =====================
% 25/12/20212 Gerard Nagle Original code
%
%Define Variables:
% a -Coefficient of the x^2 term
% b -Coefficient of the x term
% c -Constant term of the equation
% discriminant -Discriminant of the equation
% imag_part -Imag part of the equation (for complex roots)
% real_part -Real part of the equation (for complex roots)
% x1 -First Solution of equation (for real roots)

11

% x2 -Second Solution of equation (for real roots)

%prompt the user for the coefficients of the equation
disp ('This program solves for the roots of a quadratic ');
disp ('equation of the form A*X^2 + B*X + C = 0.');
a=input('Enter the coefficient A: ');
b=input('Enter the coefficient B: ');
c=input('Enter the coefficient C: ');

% Calculate the discriminant
discriminant = b^2 -4 * a * c;

%solve for the roots, depending on the values of the discriminant
if discriminant > 0 % there are two real roots, so we have
x1 = ( -b + sqrt(discriminant))/(2 *a);
x2 = ( -b - sqrt(discriminant))/(2 *a);
disp ('This equation has two real roots:')
fprintf ('x1 = %f\n', x1);
fprintf ('x2 = %f\n', x2);
elseif discriminant == 0 % there is a repeated root, so we have
x1 = ( -b )/(2 *a);
disp ('This equation has two identical roots:')
fprintf ('x1 = x2 %f\n', x1);
else % there is are complex roots, so we have
real_part = ( -b )/(2 *a);
imag_part = sqrt ( abs ( discriminant ) ) /( 2 * a );
disp ('This equation has two complex roots:')
fprintf ('x1 = %f +i %f\n', real_part, imag_part );
fprintf ('x2 = %f -i %f\n', real_part, imag_part );
end

Loop Controls
Sometimes we want MATLAB to commands or complete sections of code. This can be
achieved by using the while and for statements.
for-end statement
The for loop repeats a group of statements a fixed, predetermined number of times. A
matching end delineates the statements.
for n = 3:32
compute these commands
end
The variable n starts at a value of 3 and increases automatically for each iteration by 1 until it
reaches 33 whereupon it exits the loop without executing the commands within the loop.
The variable n could be made to increment by a different amount.
For n = 3:2:32

12

Would make n increase by 2 after each iteration.
It is a good idea to indent the loops for readability, especially when they are nested.
for i = 1:m
for j = 1:n
H(i,j) = 1/(i+j);
end
end

Example
lets use a for-end loop in a script file to calculate the sum of the first n terms of the series
( )
1
1
2
k
n
k
k
K
=

## . Check the script file for 4 n = and 20 n =

for 4 n = , the sum is -0.125 and for 20 n = the sum is -0.222216

%Script file: sum_n_terms.m
%
%Purpose
% This program calculates the sum of the n terms of the equation given in
% the text
%
%
%
%Record of revisions:
% Date Programmer Description of Change
% ==== ========== =====================
% 25/12/20212 Gerard Nagle Original code
%
%Define Variables:
% n -Number of terms
% S -The sum output

n = input('Enter the number of terms ');
S=0;
tic
for k=1:n
S=S+(-1)^k*k/(2^k);
end
toc
fprintf('The sum of the series is: %f',S)

%Function file: Tsin.m

13

..
.. MATLAB program
.
for conditional expression
..
..
..
end
Group of
MATLAB commands
for
conditional statement
START
MATLAB program
Group of
MATLAB
commands
END

The function ( ) sin x can be written as a Taylor series by the function
( )
( )
( )
2 1
0
1
sin
2 1 !
k
k
k
x
x
k
+

=
+

Write a user defined function file that calculates ( ) sin x by using the Taylors series. For the
function name and argument, use ( ) Tsin x,n y = . The input arguments are the angle x in
degrees, and n the number of terms in the series.

%Function file: Tsin.m
%
%Purpose
% This program calculates the sin(x) with input arguments of x in degrees
% and n, the number of terms in the Tatylor series
%
%
%
%Record of revisions:
% Date Programmer Description of Change
% ==== ========== =====================
% 25/12/2012 Gerard Nagle Original code
%
%Define Variables:
% x -Angle in degrees
% n -Number of terms
% y -The output

function y=Tsin(x,n)
xr = x*pi/180;
y = 0;
for k = 0:n-1
y = y + (-1)^k*xr^(2*k+1)/factorial(2*k+1);
end

14

While Statement
The while loop repeats a group of statements an indefinite number of times under the control
of a logical expression. The logical expression is tested and if it is true then the loop restarts
repeats the statements.

while expression
Repeat this code each time the expression is true
end
..
.. MATLAB program
.
while conditional expression
..
..
..
end
Group of
MATLAB commands
while
conditional statement
START
MATLAB program
Group of
MATLAB
commands
END

The function ( )
x
f x e = can be represented by the Taylor series
0
!
n
x
n
x
e
n

=
=

. We need to
write a script file that calculates
x
e by using the Taylor series. The program calculates
x
e by
adding terms of the series and stopping when the absolute value of the terms that was added
last is smaller than 0.0001. We are required to use a while-end loop, but limit the number of
passes to 30 (this is an arbitrary number). If in the 30
th
pass, the value of the term that is
added is not smaller than 0.0001, then the program stops and displays a message that more
than 30 terms are needed.

15

%Script file: taylor_series_exp(x).m
%
%Purpose
% This program solves for the exp(x) by using the Taylor series
% represenation. Thr program cacluates exp(x) by adding terms of the
% series until the absolute values of the last term added is smaller
% than 0.0001
%
%Record of revisions:
% Date Programmer Description of Change
% ==== ========== =====================
% 25/12/20212 Gerard Nagle Original code
%
%Define Variables:
% x -Value of exp(x) to be calaculated
% n -Value of incremenation of Taylor series
% an -Value of each term in the Taylor series at each loop
% S -The Sum of the Taylor series

%prompt the user for x in the exp(x)
('This program solves for exp(x) by the Taylor Series Expansion ');
x = input ('Enter x ')

%Declare the initial variables
n = 1;
an = 1;
S = an;

%Start of the while loop
%The conditional statement has two relational and one logical operator
while (abs(an) >= 0.0001) && (n <= 30)
%calcualte the nth term
an = x^n/factorial(n);
%Add the nth term to the sum
S = S + an;
%Count the number of passes
n = n + 1;
%End the while loop
end

if n >= 30
disp('Maore than 30 terms are needed')
else
fprintf('exp(%f) = %f',x,S)
fprintf('\nThe number of terms used is:%i',n)
end

Logical and relational expressions
The following are the possible relational expressions used for controlling flow
A < B (is A less than B)
A > B (is A greater than B)
A <= B (is A less than or equal to B)

16

A >= B (is A greater than or equal to B)
A = = B (is A equal to B)
A ~= B (is A not equal to B)
The logical operators are AND, OR, and NOT
A & B (is A and B true)
A | B (is A or B true)
~A (NOT A)
The following truth table determines the responses from each logical test (1 is true and 0 is
false)

Flowcharts
Flowcharts give useful graphical representations of algorithms. We can study the logic of an
algorithm if we draw its flowchart.
In the flowchart we use flow lines and shapes to distinguish the control of the algorithm.
Typical symbols used in programming are given below

Start or end of the program,
subroutine, or function
A process such as a computation or
an assignment
A decision process, where a choice is

17

Alternative to MATLAB
GNU Octave is open-source code that is Matlab portable. It will have a different interface to
Matlab, but should run the code with little or no changes required. For those who cannot get
Exercise #5
An electric motor has a power rating of 6 kW and can produce a peak torque of 27.5 Nm.
Write a function that in Matlab that returns the maximum available torque from the motor
(Nm) for any given speed (rad/s).
Use this function in a Matlab script file that plots the motor torque-speed characteristic.

A subroutine or external function that
is documented elsewhere
When it is inconvenient to connect
two points use connector with a
reference number
A counting or iterative loop, such as
a for loop

18

Ordinary Differential Equations
In mathematics, an ordinary differential equation is one which involves the derivative of a
function, the function itself, and (sometimes) the independent variable. As an example
consider the equation

( )

Where u is the dependent variable and is a function of time, t. The equation tells us that the
time rate of change of the function (or first derivative with respect to time) is dependent on
the value of u at that time and on the independent time value.
The differential equation is called ordinary because u is a function of one variable only and
the derivatives are complete, or ordinary, differentials. The order of the differential is given
by the order of the highest derivative in the equation; hence, for our example, the equation is
a first-order differential equation.
The solution of a differential equation is a function that satisfies the equation and also initial
conditions: this is known as a starting-value problem. The requirement to know the initial
conditions is determined by the order of the equation a first order equation requires one
initial condition, a second order equation requires two, and so on.
Numerical Integration Methods
For many straight-forward ODEs we can find an analytical solution to the problem, that is,
we can find a closed-form exact solution that satisfies the ODE and by adjusting some
constants we can satisfy the initial conditions. For example, the following ODE and IC

()
has the following analytical solution

However, in many cases, as the ODE becomes more complicated, the analytical solution is
unknown or too difficult to solve. In this instance a numerical solution may be your only
choice of solution.

19

Our procedure for solving an ODE numerically applies to first-order ODEs. If our underlying
equation is a higher-order ODE then we substitute for derivatives with parameters until we
get a set of first order ODEs more on this topic later.
Euler Integration
Euler integration is the simplest form of integration method. It is called a single step or
explicit method of integration, where we estimate the value of our function at the next time
using the data at the current time step. If our first order ODE is given as

( ) (

Or ( ) , y F x y ' =
Let us consider the problem of approximating a continuous function ( ) y f x = on 0 x >
which satisfies the differential equation
( ) , y F x y ' =
On 0 x > , with the initial condition
( ) 0 y o =
In which o is a given constant. Taking Eulers method, we go back to the definition of a
derivative
( )
( ) ( )
0
lim
h
f x h f x
y x
h

+
' =
For small 0 h > , then we can say that a reasonable quotient approximation for ( ) y x ' is
( )
( ) ( ) f x h f x
y x
h
+
' =
Which can be restated as
( ) ( )
( ) ,
f x h f x
F x y
h
+
=

20

It can be rewritten as
( ) ( ) ( ) , f x h f x hF x y + = +
Or equivalently as
( ) ( ) ( ) ( )
, y x h y x hF x y x + = +
Which enables us to approximate ( ) y x h + in terms of
( ) y x and ( ) ( )
, F x y x . The equation
above is a corner stone of Eulers method.
Since a computer cannot calculate indefinably, we let 0 x > be replaced by 0 x L s s , in
which L is a positive constant. The value of L is determined by the problem under
consideration. Regardless, L is a fixed, positive constant. The interval 0 x L s s is divided
into n equal parts, each a length of h , by the points , 0,1, 2,...,
i
x ih i n = = . The value
L
h
n
=
is called the grid size. The points
i
x are called grid points. Let ( ), 0,1, 2,...,
i i
y y x i n = = so
that the initial condition (IC) implies ( ) 0 y o = . Next, at each of the grid points
0 1 2 1
, , ,..., ,
n
x x x x

approximate the difference equations by the notation
( )
1
, 0,1, 2,..., 1,
i i
i i
y y
F x y i n
h
+

= =
Or, in explicit recursive form
( )
1
, 0,1, 2,..., 1,
i i i i
y y hF x y i n
+
= + =
Then, beginning with
( ) 0 y o =
Set 0 i = and determine
1
y .
Knowing
1
y , set 1 i = and determine
2
y
Knowing
2
y , set 2 i = and determine
3
y
And so on

21

The resulting discrete function
0 1 2
, , ,...,
n
y y y y
Is called the numerical solution
So, lets look at a problem.
We have the initial value problem,
y y x ' + =
( ) 0 1 y =
This is a linear problem that can be solved exactly to have the solution ( ) 1 2
x
Y x x e

= +
As there is a solution to the problem, there is no need to actually solve the equation, but we
will do so to show the technique.
So, for Eulers method, 1 L= and 0.2 h = . Then
0
0.0, x =
1
0.2, x =
2
0.4, x =
3
0.6, x =
4
0.8, x =
5
1.0 x = and the difference equation is approximated by
1
, 0,1, 2, 3, 4,
0.2
i i
i i
y y
y x i
+

+ = =
Or, if we rearrange, we get
( ) ( )
1
0.8 0.2 , 0,1, 2,3, 4,
i i i
y y x i
+
= + =
Since ( ) 0 1 y = , we can calculate the equation above
( ) ( ) ( )( ) ( )( )
( ) ( ) ( )( ) ( )( )
( ) ( ) ( )( ) ( )( )
( ) ( ) ( )( ) ( )( )
( ) ( ) ( )( ) ( )( )
1 0 0
2 1 1
3 2 2
4 3 3
5 4 4
0.8 0.2 0.8 1.000 0.2 0.0 0.800
0.8 0.2 0.8 0.800 0.2 0.2 0.680
0.8 0.2 0.8 0.680 0.2 0.4 0.624
0.8 0.2 0.8 0.624 0.2 0.6 0.619
0.8 0.2 0.8 0.619 0.2 0.8 0.655
y y x
y y x
y y x
y y x
y y x
= + = + =
= + = + =
= + = + =
= + = + =
= + = + =

Thus the numerical approximation with 0.2 h = is

22

( )
( )
( )
( )
( )
( )
0.0 1.000
0.2 0.800
0.4 0.680
0.6 0.624
0.8 0.619
1.0 0.655
y
y
y
y
y
y
=
=
=
=
=
=

The exact solution is, rounded to three decimal places
( )
( )
( )
( )
( )
( )
0.0 1.000
0.2 0.837
0.4 0.741
0.6 0.698
0.8 0.699
1.0 0.736
y
y
y
y
y
y
=
=
=
=
=
=

This can be seen in the plot below.
y
x
n
x
n
x h +
n
y
1 n
y
+
True y value from
analytical solution
y value from
Eulers Method

23

With 0.1 h = , find the numerical solution on 0 1 x s s by Eulers Method for
2 4
2 , y y x x ' = +
( ) 0 0 y =
And compare your results to the exact solution
2
y x =

With 0.1 h = , find the numerical solution on 0 2 x s s by Eulers Method for
3 3
8 2, y y x ' = + ( ) 0 0 y =
And compare your results to the exact solution 2 y x =
Modified Euler
We can improve upon the Euler integration by getting the arithmetic average of the slope at
the beginning and the end of the interval.
( )
' '
, 1 3
, 1
2
p n
c n n
y y
y y h e h
+
+
| | +
= + +
|
|
\ .

The procedure in this process is two-fold, we use the Euler method to the predict the first
value of y
p,n+1
and y
p,n+1
. We then use the above equation to calculate the corrected value of
y
c,n+1
. This method is called a predictor-corrector method and the order of the local error is
increased to three, which means that reductions in the step will yield more accurate results
that the basic Euler method.
Exercise #6
Take for example, the following ODE and IC
dy
x y
dx
= + ,
( ) 0 1 y =
Which has the following analytical solution
2 1
x
y e x =

24

We can use the analytical solution (or exact solution) to check the accuracy of our numerical
integration scheme. Note that an analytical solution is not always available and the only
method is to use a numerical method.
Let us use a table to get the answers. We shall use a integration step, h = 0.02.
n x
n
y
n
y
n
hy
n
Exact y(x)
1 0 1.0000 1.0000 0.0200 1.0000
2 0.02 1.0200 1.0400 0.0208 1.020403
3 0.04 1.041622
4 0.06 1.063673

Complete the table.
Write a piece of Matlab code that completes the integration table above
Exercise #7 Modified Euler
The procedure in this process is two-fold, we use the Euler method to the predict the first
value of y
p,n+1
and y
p,n+1
. We then use the above equation to calculate the corrected value of
y
c,n+1
. This method is called a predictor-corrector method and the order of the local error is
increased to three, which means that reductions in the step will yield more accurate results
that the basic Euler method.
We shall repeat the previous exercise using the modified Euler method.
n x
n
y
n
y
n
hy
n
y
n+1
y
n+1
' '
, 1
2
p n
y y
h
+
| | +
|
|
\ .

1 0 1.0000 1.0000 0.0200 1.0200
*
1.0400 0.0204
1.0204
**
1.0404 0.0204
2 0.02 1.0204 1.0404 0.0208 1.0412 1.0812 0.0212
1.0416 1.0816 0.0212
3 0.04 1.0416 1.0816 0.0216 1.0632 1.1232 0.0220
1.0636 1.1236 0.0221
4 0.06 1.0637 1.1237 0.02247 1.1462

25

* The first row shows the value given by the Euler method (predicted value)
** The second row in shows the value calculated by the Modified Euler (corrected value)
Complete the table and find estimated value for x = 0.08.
Write a piece of Matlab code that completes the integration table above
Runge-Kutta
A further advance on the Euler method is to use the Runge-Kutta method. Here we shall
present the fourth-order Runge-Kutta method: this one of the most widely used integration
methods.
( )
1 1 2 3 4
1
2 2
6
n n
y y k k k k
+
= + + + +
( )
1 , n n
k hf x y =
2 , 1
1 1
,
2 2
n n
k hf x h y k
| |
= + +
|
\ .

3 , 2
1 1
,
2 2
n n
k hf x h y k
| |
= + +
|
\ .

( )
4 3
,
n n
k hf x h y k = + +

26

Exercise #8
Using Matlab solve the equation
dy
x y
dx
= + ,
( ) 0 1 y =
Solve for 10 x = , this time take 0.1 h = . Compare with the exact solution.
Hint: Solution (by hand) for 0.1 x = (step 1)
Calculate
1
k
( )
1 , n n
k hf x y =
( )
1
0.1 0 1 0.100 k = + =
Calculate
2
k
2 , 1
1 1
,
2 2
n n
k hf x h y k
| |
= + +
|
\ .

( ) ( ) ( )
2
1 1
0.1 0 0.1 1 0.1 0.1 0.05 1.05 0.110
2 2
k
| | | | | |
= + + + = + =
| | |
\ . \ . \ .

Calculate
3
k
3 , 2
1 1
,
2 2
n n
k hf x h y k
| |
= + +
|
\ .

( ) ( ) ( )
3
1 1
0.1 0 0.1 1 0.110 0.1 0.05 1.055 0.1105
2 2
k
| | | | | |
= + + + = + =
| | |
\ . \ . \ .

Calculate
4
k
( )
4 3
,
n n
k hf x h y k = + +
( ) ( ) ( ) ( )
4
0.1 0 0.1 1 0.1105 0.1 0.1 1.1105 0.12105 k = + + + == + =

27

Calculate
1 n
y
+

( )
1 1 2 3 4
1
2 2
6
n n
y y k k k k
+
= + + + +
( ) ( ) ( ) ( )
1
1 1
1.0 0.1 2 0.110 2 0.1105 0.12105 1.0 0.66205 1.11034
6 6
n
y
+
= + + + + = + =