Thanks to visit codestin.com
Credit goes to www.scribd.com

0% found this document useful (0 votes)
136 views28 pages

Cuesta - Activity 2

This laboratory exercise teaches students how to solve ordinary differential equations (ODEs) using MATLAB. It covers solving first, second, and third order ODEs as well as systems of ODEs. Students will learn to obtain general and particular solutions to ODEs numerically using MATLAB's built-in solvers, including ode45 and ode23. They will solve ODEs both symbolically using dsolve and numerically using ode solvers, plotting the solutions. Examples covered include first order, second order, and systems of ODEs, as well as specifying initial conditions and domains.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
136 views28 pages

Cuesta - Activity 2

This laboratory exercise teaches students how to solve ordinary differential equations (ODEs) using MATLAB. It covers solving first, second, and third order ODEs as well as systems of ODEs. Students will learn to obtain general and particular solutions to ODEs numerically using MATLAB's built-in solvers, including ode45 and ode23. They will solve ODEs both symbolically using dsolve and numerically using ode solvers, plotting the solutions. Examples covered include first order, second order, and systems of ODEs, as well as specifying initial conditions and domains.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 28

Laboratory Exercise No.

2
SOLVING ORDINARY DIFFERENTIAL EQUATIONS USING MATLAB

1. Objective(s):
The activity aims to solve differential equations using matlab.

2. Intended Learning Outcomes (ILOs):


The students shall be able to:
2.1 solve first order ordinary differential equations using matlab
2.2 solve second order ordinary differential equations using matlab
2.3 solve third order ordinary differential equations using matlab
2.4 obtain general and particular solutions of first, second and third order ordinary differential equations
2.5 solve systems of ordinary differential equations.

3. Discussion :
Ordinary differential equations tend to arise whenever you need to model changing quantities that depend
on the amount of other quantities around it. For example, in chemistry, the time rate of change of
concentration ( dx/dt ) of a chemical solution often depends on the concetrations of other chemicals that
surround it. In biology, differential equations are often used in population dynamics, to model the evolution
and/or extinction of a particular species (like people, animals, bacteria, or even viruses like HIV) (eg.,
Volterra Equations). In finance, the stock market is often modeled via sets of coupled differential equations
(e.g., Black-Scholes equation). In physics, dfq's are everywhere { we've seen them in Cosmology (e.g.,
Friedmann's Equations, non-linear structure growth and perturbation theory), Classical Dynamics (e.g., the
orbits of planets, stars, and galaxies as specialized N-body problems, hydrodynamics),and Radioactive
Transfer. Most differential equations are too complicated to write down a solution by hand (an "analytical
solution"), so one has to revert to numerics to find any kind of solution at all.
Numerical methods are commonly used for solving mathematical problems that are formulated in
science and engineering where it is difficult or even impossible to obtain exact solutions. Only a limited
number of differential equations can be solved analytically. Numerical methods, on the other hand, can give
an approximate solution to (almost) any equation. An ordinary differential equation (ODE) is an equation
that contains an independent variable, a dependent variable and derivatives of the dependent variable.

The MATLAB ODE solvers are written to solve problems of the form

dx/dt = F(t,x)

The Matlab ODE solvers are accesses by calling a function of the form

[X,T] = ode** (@F, TimeSpan,Xo,Options,P1,P2,P3)

@F A handle to a function which returns a vector of


rates of change

Timespan A row vector of times at which the solution is


needed OR a vector of the form [start,end]
Xo A vector of initial values

Options (if omitted or set to [], the default A data structure which allows the user to set
settings are used various options associated with the ode solver

P1,P2,P3.. These are additional arguments which will be


passed to @F

F must have the following form

Function [dx_dt] = F(t,x,P1,P2,P3)

dx_dt =

return

There are several different ode solvers supplied with matlab.

Solver Implicit/Explicit Accuracy

ode45 Explicit 4th order, medium accuracy

ode23 Explicit 2nd/3rd order, low accuracy

ode113 Explicit Very accurate 913th order)

ode15s Implicit Anything from 1st-5th order

ode23s Implicit Low accuracy (but may be more


stable than ode15s)

ode23tb Implicit Low accuracy (but may be more


stable than ode15s)

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

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)


9. Plotting this solution can be accomplished as follows:

>> t = linspace (0,0.5,25);

>> xx = eval(vectorize(x));

>> yy = eval(vectorize(y));

>> zz = eval(vectorize (z));

>> plot (t,xx,t,yy,t,zz)

Press enter and record the results.

10. To find numerical solutions, MATLAB has a number of tools for numerically solving ordinary
differential equations. Built-in functions ode23 and ode45, which implement versions of Runge-
Kutta 2nd/3rd order and Runge-Kutta 4th and 5th order, respectively. Numerically approximate the
solution of the first order differential equation

dy/dx = xy 2 + y ; y(0) =1 on the interval x [0,0.5]

For any differential equation in the form y = f(x,y), we begin by defining the function f(x,y). For
single equations, we can define f(x,y) as an inline function

>> f = inline(x*y^2 + y)

Press enter and record the results.

11. The basic usage for MATLABs solver ode45 is ode45(function, domain, initial condition). That is ,
we use

>>[x,y] = ode45(f,[0,0.5],1)

Press enter and record the results.

12. To plot the values

>>plot(x,y)

Press enter and record the results.

13. Choosing the partition. In approximating this solution, the algorithm ode 45 has selected a certain
partition [0,0.5] and MATLAB has returned a value of y at each point in this partition. It is often the
case that we would like to specify the partition of values on which MATLAB returns an
approximation. For example, we might only want to approximate y(0.1),y(0.2) y(0.5).We can
specify this by entering the vector values [0,0.1,0.2,0.3,0.4,0.5] as the domain in ode45. That is, we
use

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

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.

19. We can also plot each component of the solution as a function of t

>>subplot(3,1,1)

>>plot(t,x(:,1))

>>subplot(3,1,2)

>>plot(t,x(:,2)

>>subplot(3,1,3)

>>plot(t,x(:,3)

20. In analyzing system of differential equations, we often want to experiment with different parameter
values. For example, in studying the Lorenz equations we might want to consider the behavior as a
function of the values of , and . Of course, one way to change this is to manually re-open the
M-file Lorenz.m each time we want to try new values, but not only is a slow way to do it, its
unwieldy to automate it. What we can do instead is pass parameter values directly to our M-file
through the ode45 call statement.Alter Lorenz.m into lorenz1.m, the latter of which accepts a vector
of parameters that we denote p.

Function xprime = lorenz1(t,x,p);

%LORENZ ; Computes the derivatives involved in solving the Lorenz equations.

sig=p(1);beta=p(2);rho=p(3);

xprime=[-sig*x(1) + sig*x(2);rho*x(1)-x(2)-x(1)*x(3);-beta*x(3) +x(1)*x(2)];


21. We can now send parameter values with ode45

>>p=[10 8/3 28];

>>[t,x]=ode45(@lorenz1,tspan,x0,[],p)

Press enter and record the results.

22. The first step in solving a second (or higher) order ordinary differential equation in MATLAB is to
write the equation as a first order system. For the equation

y(x) + 8y(x) + 2y(x) = cos(x) ; y(0) = 0 , y(0)=1

Taking y1(x) = y(x) and y2(x) = y(x)

y1(x) = y2(x)

y2 (x) = -8y2(x) -2y1(x) + cos(x)

Proceed as in Procedure 16.

23. Another class of ODEs that often arise in applications are boundary value problems (BVPs).
Consider ,for example, the differential

y 3y + 2y = 0

y(0) = 0

y(1)=10

where our conditions y(0)=0 and y(1) = 10 are specified on the boundary of the interval of

interest

interest x [0,1]. The first step in solving this type of equation is to write it as a first order system

with y1 = 1 and y2 = y, for which we have

y1 = y2

y2 = -2y1 + 3y2

24. We record this system in the M-file bvpexample.m

Function yprime = bvpexample(t.y)

%BVPEXAMPLE : Differential equation for boundary value problem example


yprime=[y(2); -2*y(1) + 3*y(2)];

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 :

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.

Function dy= ilovecats(t,y)

dy = zeros(1,1);

dy = -5 * y;

Now create another file and save it as happyscript.m.

[t,y]=ode45(ilovecats,[0,10],1.43);

plot(t,y,-)

xlabel(time);

ylabel(y(t));

title(This plot dedicated to kitties everywhere);

30. Type help ode45 at the prompt. As a general rule of thumb, ode45 is the best function to apply as
a first try for most problems. Ode 45 is an explicit (4,5) Runge-Kutta integrating technique.At
Matlab prompt, type happyscript.m. Press enter and record the results.

31. A 2nd order differential equation is one where the highest derivative term is of order 2:

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;

dy(1) = y(2);

dy(2) = -omega*omega*sin(y(1));

33. Create another m file and save it as pendulumcatscript.m.

[t,y] = ode45(pendulumcats,[0,25],[1.0 1.0 ]);

plot(t,y(:,1),-);

xlabel (time);

ylabel(y_{1}(t));

title(\theta (t));

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,
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);

38. The script file lorenzscript.m should look like:

[t,y] = ode45(lorenz, [0 250], [1.0 1.0 1.0];

subplot(221)
plot (y(:,1),y(:,2),-);

xlable(x(t));

ylabel(y(t));

title( Phase Plane Portrait for Lorenz attractor y(t) vs x(t));

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

Run the script and record the results.

41. The Matlab code to solve dy/dx = y(x) with no initial conditions is shown below:

ODE1= dy = y

ODE1solved=dsolve(ODE1, x)

Record the results.

42. To specify initial conditions for the ODE is as follows :

initConds = y(0) = 5

ODE1solved = dsolve(ODE1, initConds,x)

Record the results.

43. Matlab makes plotting functions easy. To plot the function:

x = -5:0.01:5;

y_values = eval(vectorize(ODE1solved);

plot(x,y_values)

Record the results.

44. The same ideas apply to higher ODEs. To solve a second-order ODE with initial values at y(0) and
y(0).Then plot the function in the range [-5,5]

ODE2 = 3*D2y Dy + 6*y = 6 *sin(t) + 2 *cos(t)

initConds = y(0)=1, Dy(0)=2

ODE2solved = simplify)dissolve(ODE2,initConds));

pretty(ODE2solved)
t=-5 :0.01:5;

y_values=eval(vectorize(ODE2solved));

plot(t,y_values)

Record the results.

45. Systems of ODEs can be solved in a similar manner.One simply defines each equation as before.
The only thing that changes is the return of the dsolve function, which is now an array containing
the explicit solutions of each of the functions in the system

sysODE1 = Dx = 2*x + 3*z

sysODE2 = Dy = 6*z y

sysODE3 = Dz = 3*y 12*x

initConds = x(1) = 5, y(2)=3, z(9) = 0

[x,y,z] = dsolve(sysODE1,sysODE2,sysODE3,initConds)

Record the results


Course: CHE 508 Laboratory Exercise No.: 2
Group No.: Section: CH51FC1
Group Members: Date Performed: June 21, 2017
Cuesta, Alwyn Wren C. Date Submitted: June 28, 2017
Instructor: Engr. Crispulo Marana

6. Data and Results:

Procedure No. MATLAB Result


1 N/A
2 >> y = dsolve('Dy = y*x','x')

y=

C1*exp(x^2/2)

>> y = dsolve('D2y = y*x','x')

y=

C2*airy(0, x) + C3*airy(2, x)
3 >> eqn1 = 'Dy=y*x';
>> y = dsolve(eqn1,'x')

y=

C1*exp(x^2/2)
4 >> y = dsolve(eqn1,'y(1)=1','x')

y=

exp(-1/2)*exp(x^2/2)
5 >> x = linspace(0,1,20);
>> z = eval(vectorize(y));
>> plot(x,z)
6 N/A
7 >> eqn2 = 'D2y + 8*Dy + 2*y = cos(x)';
>> inits2 = 'y(0)=0, Dy(0) = 1';
>> y = dsolve(eqn2,inits2,'x')

y=

(14^(1/2)*exp(4*x - 14^(1/2)*x)*exp(x*(14^(1/2) - 4))*(sin(x) - cos(x)*(14^(1/2) -


4)))/(28*((14^(1/2) - 4)^2 + 1)) - (14^(1/2)*exp(4*x + 14^(1/2)*x)*exp(-x*(14^(1/2) +
4))*(sin(x) + cos(x)*(14^(1/2) + 4)))/(28*((14^(1/2) + 4)^2 + 1)) - (14^(1/2)*exp(-
x*(14^(1/2) + 4))*(7*14^(1/2) + 27))/(28*(8*14^(1/2) + 31)) - (14^(1/2)*exp(x*(14^(1/2)
- 4))*(393*14^(1/2) + 1531))/(28*(8*14^(1/2) - 31)*(8*14^(1/2) + 31)^2)
8 >> [x,y,z] =dsolve('Dx = x + 2*y-z','Dy = x + z',' Dz = 4*x - 4*y + 5*z')

x=

- (C7*exp(t))/2 - (C8*exp(2*t))/2 - (C9*exp(3*t))/4

y=

(C7*exp(t))/2 + (C8*exp(2*t))/4 + (C9*exp(3*t))/4

z=

C7*exp(t) + C8*exp(2*t) + C9*exp(3*t)


9 >> t = linspace(0,0.5,25);
>> xx = eval(vectorize(x));
>> yy = eval(vectorize(y));
>> zz = eval(vectorize(z));
>> plot (t,xx,t,yy,t,zz)

10 >> f = inline('x*y^2 + y')

f=
Inline function:
f(x,y) = x*y^2 + y
11 > [x,y] = ode45(f,[0,0.5],1)

x=

0
0.0125
0.0250
0.0375
0.0500

0.4500
0.4625
0.4750
0.4875
0.5000

y=

1.0000
1.0127
1.0256
1.0390
1.0526

1.8182
1.8605
1.9048
1.9512
2.0000
12 >> plot(x,y)

13 > xvalues = 0:.1:.5


xvalues =

0 0.1000 0.2000 0.3000 0.4000 0.5000

>> [x,y]= ode45(f,xvalues,1)

x=

0
0.1000
0.2000
0.3000
0.4000
0.5000

y=

1.0000
1.1111
1.2500
1.4286
1.6667
2.0000
14 >> [x,y] = ode45(f,[0,1],1);
Warning: Failure at t=9.999897e-01. Unable to meet integration
tolerances without reducing the step size below the smallest
value allowed (1.776357e-15) at time t.
> In ode45 (line 308)
>> options = odeset('RelTol',1e-10);
>> [x,y] = ode45(f,[0,1],1,options);
>> max(y)

ans =

2.4251e+07
15 >> xspan = [0,.5];
>> y0=1;
>> [x,y]=ode23(@firstode,xspan,y0);
>> x

x=

0
0.0500
0.1000
0.1500
0.2000
0.2500
0.3000
0.3500
0.4000
0.4500
0.5000
16 %ON SCRIPT WINDOW
function xprime = Lorenz(t,x);
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 >> [t,x] = ode45(@Lorenz,tspan,x0);
>> x0 = [-8 8 27];
>> tspan = [0,20];
>> [t,x] = ode45(@Lorenz,tspan,x0)

t=

0
0.0025
0.0050
0.0075
0.0100

19.9622
19.9717
19.9811
19.9906
20.0000

x=

-8.0000 8.0000 27.0000


-7.6036 7.9571 26.6639
-7.2182 7.9093 26.3387
-6.8436 7.8574 26.0242
-6.4796 7.8021 25.7199

9.2111 13.9471 20.4867
9.6611 14.4499 21.2271
10.1138 14.9053 22.0533
10.5640 15.2991 22.9618
11.0058 15.6163 23.9464
18 >> plot(x(:,1),x(:,3))

19 >> subplot(3,1,1)
>> plot(t,x(:,1))
>> subplot(3,1,2)
>> plot(t,x(:,2))
>> subplot(3,1,3)
>> plot(t,x(:,3))

20 %ON SCRIPT WINDOW


Function xprime = lorenz1(t,x,p);
sig = p(1); beta = p(2); rho = p(3);
xprime = [-sig*x(1) + sig*x(2); rho*x(1) - x(2) - x(1)*x(3); -beta*x(3) + x(1)*x(2)];
21 >> p=[10 8/3 28];
>> [t,x]=ode45(@lorenz1,tspan,x0,[],p)

t=

0
0.0025
0.0050
0.0075
0.0100

19.9722
19.9717
19.9811
19.9906
20.0000

x=

-8.0000 8.0000 27.0000


-7.6036 7.9571 26.6639
-7.2182 7.9093 26.3387
-6.8436 7.8574 26.0242
-6.4796 7.8021 25.7199

9.2111 13.9471 20.4867
9.6611 14.4499 21.2271
10.1138 14.9053 22.0533
10.5640 15.2991 22.9618
11.0058 15.6163 23.9464
22 26 >> sol = bvpinit(linspace(0,1,25),[0 1]);
>> sol = bvp4c(@bvpexample,@bc,sol);
>> sol.x

ans =

Columns 1 through 6

0 0.0417 0.0833 0.1250 0.1667 0.2083

Columns 7 through 12

0.2500 0.2917 0.3333 0.3750 0.4167 0.4583

Columns 13 through 18

0.5000 0.5417 0.5833 0.6250 0.6667 0.7083

Columns 19 through 24

0.7500 0.7917 0.8333 0.8750 0.9167 0.9583

Column 25

1.0000
28 - 30 >> help ode45
ode45 Solve non-stiff differential equations, medium order method.
[TOUT,YOUT] = ode45(ODEFUN,TSPAN,Y0) with TSPAN = [T0 TFINAL]
integrates
the system of differential equations y' = f(t,y) from time T0 to TFINAL
with initial conditions Y0. ODEFUN is a function handle. For a scalar T
and a vector Y, ODEFUN(T,Y) must return a column vector corresponding
to f(t,y). Each row in the solution array YOUT corresponds to a time
returned in the column vector TOUT. To obtain solutions at specific
times T0,T1,...,TFINAL (all increasing or all decreasing), use TSPAN =
[T0 T1 ... TFINAL].

[TOUT,YOUT] = ode45(ODEFUN,TSPAN,Y0,OPTIONS) solves as above with


default
integration properties replaced by values in OPTIONS, an argument created
with the ODESET function. See ODESET for details. Commonly used options
are scalar relative error tolerance 'RelTol' (1e-3 by default) and vector
of absolute error tolerances 'AbsTol' (all components 1e-6 by default).
If certain components of the solution must be non-negative, use
ODESET to set the 'NonNegative' property to the indices of these
components.

ode45 can solve problems M(t,y)*y' = f(t,y) with mass matrix M that is
nonsingular. Use ODESET to set the 'Mass' property to a function handle
MASS if MASS(T,Y) returns the value of the mass matrix. If the mass matrix
is constant, the matrix can be used as the value of the 'Mass' option. If
the mass matrix does not depend on the state variable Y and the function
MASS is to be called with one input argument T, set 'MStateDependence' to
'none'. ODE15S and ODE23T can solve problems with singular mass matrices.

[TOUT,YOUT,TE,YE,IE] = ode45(ODEFUN,TSPAN,Y0,OPTIONS) with the


'Events'
property in OPTIONS set to a function handle EVENTS, solves as above
while also finding where functions of (T,Y), called event functions,
are zero. For each function you specify whether the integration is
to terminate at a zero and whether the direction of the zero crossing
matters. These are the three column vectors returned by EVENTS:
[VALUE,ISTERMINAL,DIRECTION] = EVENTS(T,Y). For the I-th event function:
VALUE(I) is the value of the function, ISTERMINAL(I)=1 if the integration
is to terminate at a zero of this event function and 0 otherwise.
DIRECTION(I)=0 if all zeros are to be computed (the default), +1 if only
zeros where the event function is increasing, and -1 if only zeros where
the event function is decreasing. Output TE is a column vector of times
at which events occur. Rows of YE are the corresponding solutions, and
indices in vector IE specify which event occurred.

SOL = ode45(ODEFUN,[T0 TFINAL],Y0...) returns a structure that can be


used with DEVAL to evaluate the solution or its first derivative at
any point between T0 and TFINAL. The steps chosen by ode45 are returned
in a row vector SOL.x. For each I, the column SOL.y(:,I) contains
the solution at SOL.x(I). If events were detected, SOL.xe is a row vector
of points at which events occurred. Columns of SOL.ye are the corresponding
solutions, and indices in vector SOL.ie specify which event occurred.

Example
[t,y]=ode45(@vdp1,[0 20],[2 0]);
plot(t,y(:,1));
solves the system y' = vdp1(t,y), using the default relative error
tolerance 1e-3 and the default absolute tolerance of 1e-6 for each
component, and plots the first component of the solution.

Class support for inputs TSPAN, Y0, and the result of ODEFUN(T,Y):
float: double, single

See also ode23, ode113, ode15s, ode23s, ode23t, ode23tb, ode15i,


odeset, odeplot, odephas2, odephas3, odeprint, deval,
odeexamples, rigidode, ballode, orbitode, function_handle.

Reference page for ode45


31 - 35 >> y

y=

1.0000
1.0526
1.1111
1.1765
1.2500
1.3333
1.4286
1.5384
1.6666
1.8181
1.9999

>> y(:,1)

ans =

1.0000
1.0526
1.1111
1.1765
1.2500
1.3333
1.4286
1.5384
1.6666
1.8181
1.9999

>> y(:,2)
Index exceeds matrix dimensions.
41 >> ODE1= 'dy = y'

ODE1 =

dy = y

>> ODE1solved=dsolve(ODE1, 'x')

ODE1solved =

C2*exp(x)
42 >> initConds = y(0) = 5

initConds =

y(0) = 5

>> ODE1solved = dsolve(ODE1,initConds, x)

ODE1solved =

5*exp(x)
43 >> x = -5:0.01:5;
>> y_values = eval(vectorize(ODE1solved));
>> plot(x,y_values)
45 >> sysODE1 = 'Dx = 2*x + 3*z'

sysODE1 =

Dx = 2*x + 3*z

>> sysODE2 = 'Dy = 6*z - y'

sysODE2 =

Dy = 6*z y

>> sysODE3 = 'Dz = 3*y - 12*x'

sysODE3 =

Dz = 3*y - 12*x

>> initConds = 'x(1) = 5, y(2)=3, z(9) = 0'

initConds =

x(1) = 5, y(2)=3, z(9) = 0

7. Conclusion:
I therefore conclude that MATLAB is a very powerful software as it can solve a lot of differential equations
and matrix equations. In this lab activity, I discovered a lot of new useful MATLAB codes and commands
that I could use whenever Im solving differential equations and I also got a lot more used now in using the
m-file as we only had little knowledge on script window before. With these newfound knowledge about
MATLAB, I feel solving differential equations on my upcoming 5 th year chemical engineering designs will be
faster and better for a powerful tool such as MATLAB now belongs to my arsenal of skills.
8. Assessment (Rubric for Laboratory Performance):

You might also like