Documenti di Didattica
Documenti di Professioni
Documenti di Cultura
CHEP530D1
Computer Applications in Engineering
Timespan
Xo
P1,P2,P3..
Solver
Implicit/Explicit
Accuracy
ode45
Explicit
ode23
Explicit
ode113
Explicit
ode15s
Implicit
ode23s
Implicit
ode23tb
Implicit
ODE45 (an explicit Runge-Kutta method) is efficient, but can become unstable with stiff systems.
This will manifest itself by the solver taking shorter and shorter time steps to compensate. The
solution will either take a long time, or the time step will be reduced to the point where machine
precision causes the routine to fail.
The problems of solving an ODE are classified into initial-value problems (IVP) and
boundary value problems (BVP), depending on how the conditions at the endpoints of the domain
are specified. All the conditions of an initial-value problem are specified at the initial point. On the
Laboratory Exercise no. 2
Solving Ordinary Differential Equations Using Matlab
other hand, the problem becomes a boundary-value problem if the conditions are needed for both
initial and final points. The ODE in the time domain are initial-value problems, so all the conditions
are specified at the initial time, such as t = 0 or x = 0. For notations, we use t or x as an
independent variable.Some literatures use t as time for independent variable.
4. Resources:
Matlab
5. Procedure:
1. Though Matlab is primarily a numeric package, it can solve straightforward differential equations
symbolically. Suppose, for example, we want to solve the first order differential equation y = xy
where y = dy/dx =y(x).
2. We can use Matlabs built-in dsolve(). The input for solving this problem in Matlab is given below:
>>y = dsolve(Dy = y*x,x) where y(x) must be written as Dy. If it is y (x), same as d 2 y/ x 2 ,it
must be written as D2y.If it is y(x), same as d 3 y/ x3 , it must be written as D3y. It is 8y(x), same
as 8dy/dx, it must be written as 8*Dy. All in Java command window. Press enter and record the
results.
3. Notice in particular that MATLAB uses capital D to indicate the derivative and requires that the
entire equation appear in single quotes. MATLAB takes t to be the independent variable by default,
so here x must be explicitly defined as the independent variable. Alternatively, if you are going to
use the same equation a number of times, you might choose to define it as a variable, say eqn 1.
>>eqn1 = Dy=y*x;
>>y = dsolve(eqn1,x)
Press enter and record the results.
4. To solve an initial value problem, say, y(x)=xy with y(1)=1 use
>>y =dsolve (eqn1,y(1)=1,x)
Press enter and record the results.
5. To plot the solution to get a rough idea of its behavior.
>>x = linspace(0,1,20);
>>z= eval(vectorize(y));
>>plot(x,z)
Press enter and record the results.
Laboratory Exercise no. 2
Solving Ordinary Differential Equations Using Matlab
6. Suppose we want to solve and plot the solution to the second order equation
y(x) + 8y(x) + 2y(x) = cos(x) ; y(0) = 0 , y(0)=1
7. The following MATLAB code suffices:
>>eqn2 = D2y + 8*Dy + 2*y = cos(x);
>>inits2 = y(0)=0, Dy(0) = 1;
>>y = dsolve(eqn2,inits2,x)
Press enter and see the results. Record the results.
>>z = eval(vectorize(y));
>>plot(x,z)
Press enter and record the results.
8. Suppose we want to solve and plot the solutions to the system of three ordinary differential
equations
x(t) = x(t) + 2y(t) z(t)
y(t) = x(t) + z(t)
z(t) = 4x(t) 4y(t) + 5z(t)
To find a general solution, each equation is now braced in its own pair of (single) quotation marks:
>> [x,y,z] = dsolve(Dx = x +2*y-z,Dy = x + z,Dz = 4*x 4*y + 5*z)
Press enter and record the results. Notice that since no independent variable is specified,
MATLAB used its default, t.
With conditions:
>> inits = x(0)=1, y(0)= 2, z(0)=3;
>> [x,y,z] = dsolve(Dx = x +2*y-z,Dy = x + z,Dz = 4*x 4*y + 5*z,inits)
>>xvalues = 0:.1:.5
Press enter and see the results. Record the results.
>>[x,y]=ode45(f,xvalues,1)
Press enter and record the results.
14. Several options are available for MATLABs ode45 solver, giving the user limited control over the
algorithm.Two important options are relative and absolute tolerance, respectively RelTol and AbsTol
in MATLAB. At each step of the ode45 algorithm, an error is approximated for that step. If y k is the
approximation of y(xk) at step k, and ek is the approximate error at this step, then MATLAB chooses
its partition to insure
ek max(RelTol *yk , AbsTol)
where the default values are RelTol=.001 and AbsTol=.000001. As an example for when we might
want to change these values, observe that if yk becomes large, then the error ek will be allowed to
grow quite large. In this case, we increase the value of RelTol. For the equation y = xy 2 + y, with
y(0)=1, the values of y get quite large as x near 1. In fact, with the default error tolerances, we find
that the command
>> [x,y] = ode45(f,[0,1],1);
Leads to an error message,caused by the fact that the values of y are getting too large as x nears
1.In order to fix this problem,we choose a smaller value for RelTol
>>options = odeset(RelTol,1e-10);
>>[x,y]=ode45(f,[0,1],1,options);
>>max(y)
Press enter and record the results.
15. Alternatively, we can solve the same ODE by first defining f(x,y) as an M-file firstode.m
function yprime = firstode(x,y);
% FIRSTODE: Computes yprime =x*y^2 + y
yprime = x*y^2 + y;
In this case, we only require one change in the ode45 command: we must use a pointer @ to
indicate the m-file. That is, we use the following commands
>>xspan=[0,.5];
>>y0=1;
>.[x,y]=ode23(@firstode,xspan,y0);
>>x
Press enter and record the results.
16. Solving a system of ODE in MATLAB is quite similar to solving a single equation, though since a
system of equations cannot be defined as an inline function we must define it as an M-file. Solve
the system of Lorenz equations,
dy/dt = -x + y
dy/dt = x y -xz
dy/dt = -z + xy
where for the purposes of this example, we will take = 10, = 8/3, and =28, as well as x(0)=-8,
y(0)=8, and z(0)=27. The MATLAB M-file containing the Lorenz equations appears below
function xprime = Lorenz(t,x);
%LORENZ: Computes the derivatives involved in solving the Lorenz equations
sig = 10;
beta = 8/3;
rho=28;
xprime=[-sig*x(1) + sig*x(2);rho*x(1)-x(2)-x(1)*x(3);-beta*x(3) +x(1)*x(2)];
17. Observe that x is stored as x(1), y is stored as x(2) and z is stored as x(3).Additionally, xprime is a
column vector,as is evident from semicolon following appearance of x(2).In the command
window,we type
>>x0=[-8 8 27];
>>tspan=[0,20];
>>[t,x]= ode45(@lorenz,tspan,x0)
Press enter and record the results.
Laboratory Exercise no. 2
Solving Ordinary Differential Equations Using Matlab
18. The matrix has been denoted x in the statement calling ode45, and in general any coordinate of the
matrix can be specified as x(m,n) where m denotes the row and n denotes the column.What we
will be most interested in is referring to the columns x, which correspond with values of the
components of the system. Along these lines, we can denote all row or all x by a colon : . For
example, x(:,1) refers to all rows in the first column of the matrix x; that is, it refers to all values of
our original x component. Using this information, we can easily plot the Lorenz strange attractor,
which is a plot of z versus x:
>>plot(x(:,1),x(:,3))
Press enter and record the results.
25. Next , we write the boundary conditions as the M-file bc.m, which records boundary residues
Function res = bc(y0,y1)
%BC: Evaluates the residue of the boundary condition
Res=[y0(1);y1(1)-10];
By residue, we mean the left-hand side of the boundary condition once it has been set to 0.In this
case, the second boundary condition is y(1)=10, so its residue is y(1)-10, which is recorded in the
second component of the vector that bc.m returns The variables y0 and y1 represent the solution
at x=0 and at x=1 respectively, while the 1 in the parenthesis indicates the first component of the
vector. In the event that the second boundary condition was y(1) = 10, we would replace y1(1)-10
with y1(2)-10.
26. We are now in a position to begin solving the boundary value problem. In the following code, we
first specify a grid of x values for MATLAB to solve on and an initial guess for the vector that would
be given for an initial value problem [y(0),y(0)].We solve the boundary value problem with
MATLABs built-in solver bvp4c.
>>sol = bvpinit(linspace(0,1,25),[0 1]);
>>sol = bvp4c(@bvpexample,@bc,sol);
>>sol.x
Press enter and record the results.
27. We observe that in this case MATLAB returns the solution as a structure whose first component
sol.x simply contains the x values we specified.The second component of the structure sol is sol.y,
which is the matrix containing as its first row values of y(x) at the grid points we specified, and as
its second row the corresponding values of y(x).
28. For the first order differential equation where the highest derivative of the function is one :
dy
=5 y
dx
From calculus, we all know that the solution to this equation is y(t) = Ce -5t, where C is some arbitrary
constant. If we specified an initial condition (say, y(0)= 1.43), then our analytical solution would be
y(t) = 1.43 e-5t.
29. In Matlab, we can use numerical integration techniques to solve differential equations like this
one.For the differential equation in Procedure No. 28, you would make two .m files (one will be a
function file, and the other will be a script that calls the function file).Using Matlab editor, create the
file below and save it as ilovecats.m.
Laboratory Exercise no. 2
Solving Ordinary Differential Equations Using Matlab
31. A 2nd order differential equation is one where the highest derivative term is of order 2:
2
d2 y
sin
=
()
dt2
To integrate this in Matlab, we have to rewrite this single equation into a set of 2 first order
differential equations. The reason behind this is because all Runge-Kutta solvers, including ode45,
are built to only integrate over equations of the type dy/dt = f(t,y).We can easily do this by hand, by
setting:
dy1/ dt = y2
dy2/dt = - 2 sin(y1)
where y1(t) represents (t), and y2(t) represents d/dt.
32. Create an m file and save it as pendulumcats.m
function dy = pendulumcats(t,y)
dy = zeros(2,1);
omega = 1;
Laboratory Exercise no. 2
Solving Ordinary Differential Equations Using Matlab
dy(1) = y(2);
dy(2) = -omega*omega*sin(y(1));
figure;
plot(t,y(:,2),'-');
xlabel('time');
ylabel('y_{2}(t)');
title('d \theta / dt (t)');
figure;
plot(y(:,1),y(:,2),'-');
xlabel('\theta (t)');
ylabel('d \theta / dt (t)');
title('Phase Plane Portrait for undamped pendulum');
34. The change in the function file, pendulumcats.m, is the initialization part in line two dy =
zeros(2,1); This is because we now have two equations we are integrating over (y1(t) and y2(t), so
Matlab will store their data into a matrix with two columns.If you just type y at your Matlab prompt,
you will get two columns of data that display.The first column is the set of y(t) (or y1(t)), whose data
points you can alone access by typing y(:,1) at your prompt.The second column of y are the
datapoints for y2(t), which you can access by themselves by typing y(:,2) at your prompt.
35. Run the commands. Record the results.
36. Back in the day, scientists didn't know as much, and thought they could accurately predict the
weather once computers became more powerful. This is because weather people used many sets
of differential equations to model the weather, and it took a long time to integrate those equations
(keep in mind that awesome things like Matlab weren't around in the 50s and 60s { people still used
slide rulers and tables to calculate many things, and the computers that were available back in the
day had very little computing power, so integrating some ODEs, like those in the pendulum
example, would take a crazy long time for the computer to chug through!).
Edward Lorenz was a mathematician and weather forecaster for the US Army Air Corps,
Laboratory Exercise no. 2
Solving Ordinary Differential Equations Using Matlab
and later an MIT professor. For many years, he was interested in solving a simple set of 3 coupled
differential equations just because he wanted to find out what the weather would be like during the
next week." These equations are called the Lorenz Equations, and were derived from simplified
equations of convection rolls rising in the atmosphere. They are pretty simple and can be
expressed as:
dx/dt = -Px + Py
dy/dt = rx y xz
dz/dt = xy bz
where P, r and b are all constants ( P represents the Prandtl number, and r is the ratio of Rayleigh
number to the critical Rayleigh number), and x, y and z are all functions of time. We can use Matlab
to look at trajectories (i.e. plots of x(t) vs time, y(t) vs. time and z(t) vs. time) or phase plane
portraits (i.e. x(t) vs y(t), x(t) vs z(t), and/or y(t) vs z(t) for this system.
37. The function file lorenz.m) should look like:
function dy = lorenz(t,y)
dy = zeros(3,1);
P=10;
r=28;
b=8/3
dy(1)=P*(y(2)-y(1));
dy(2)=-y(1)*y(3) + r*y(1) y(2);
dy(3) = y(1)*y(2) b*y(3);
subplot(222)
plot(y(:,1),y(:,3),-);
xlabel(x(t));
ylabel( z(t));
title(Phase Plane Portrait for Lorenz attractor z(t) vs x(t));
subplot(223)
plot( y(:,2),y(:,3,)-);
xlabel(y(t));
ylabel(z(t));
title(Phase Plane Portrait for Lorenz attractor z(t) vs y(t));
suplot(224)
plot(0,0,.);
xlabel(Edward Lorenz);
ylabel(Kitties);
title(Kitties vs Lorenz);
39. Run the script.It should take a little while to run. Record the results.
40. To make a 3D plot ,add the following to the bottom of the script.
plot3(y(:,1),y(:,2),y(:,3),-)
xlabel(x(t));
ylabel(y(t));
zlabel(z(t));
title(3D phase portrait of Lorenz Attractor);
Laboratory Exercise no. 2
Solving Ordinary Differential Equations Using Matlab
Course: BS ChE
Group No.:
Group Members:
Date Performed:
Date Submitted: June 29, 2015
Instructor: Engr. Crispulo Maranan
Matlab Result
10
11
12
13
14
15
16-17
18
45
40
35
30
25
20
15
10
5
-20
-15
-10
-5
10
15
20
19
20
0
-20
10
12
14
16
18
20
10
12
14
16
18
20
0.1
0.2
0.3
0.4
0.5
0.6
0.7
0.8
0.9
50
0
-50
1
0.5
0
21-22
23-26
27-30
31-35
36-39
40
41
42
43
44
45
7. Conclusion:
Matlab software is an application that can help any person solving difficult ordinary differential equations.
T I P V P A A 0 5
4 D
CRITERIA
BEGINNER
1
ACCEPTABLE
2
PROFICIENT
3
SCORE
I. Laboratory Skills
Manipulative
Skills
Members do
needed skills.
not
demonstrate
Members always
needed skills.
demonstrate
Experimental Set-up
Process Skills
Safety Precautions
Time Management /
Conduct of Experiment
Cooperative
Teamwork
and
Members
have
defined
responsibilities most of the time.
Group conflicts are cooperatively
managed most of the time.
Neatness
Orderliness
and
Ability to do independent
work
Members
require
occasional
supervision by the teacher.
TOTAL SCORE
Other Comments / Observations:
TotalScore
RATING = (
24
) x 100%
Evaluated by:
_______________________________________
Printed Name and Signature of Faculty Member
Laboratory
Exercise
no. 2
3
Date:
___________________________
June 29, 2015