SlideShare ist ein Scribd-Unternehmen logo
1 von 42
Using ODEs in MATLAB 
Prepared By: Nahla Al Amoodi 
17th September 2007
ODEs 
 The initial value problem for an ordinary 
differential equation involves finding a 
function y(t) that satisfies: 
With the initial condition y(t0)=y0 
A numerical solution generates a sequence of values for the 
independent variable, and a corresponding sequence of values for 
the dependent variable, such that each yn approximates the solution 
at tn.
Euler’s Method 
 Works mainly for simple first order differential 
equations. 
 Consider the following equation: 
and y(0) given 
f (x, y) 
dy 
dx 
 
 This differential can be replaced with its 
Newton quotient:
Euler’s Method 
( , ) 
y x h y x 
( ) ( ) 
f x y 
h 
 
  
Rearranging: 
y(x  h)  y(x)  hf (x, y)    (1) 
Developing an iterative scheme: 
( , ) i 1 i i i y  y  hf x y  
Where ( ) i i y  y x
Euler’s Method 
Where ( ) i i y  y x 
 such that at the 
beginning of step i, 
( 1) (0) 1 x i h and y y i    
Suppose that the ode is to be integrated over the 
interval from x=a to x=b. This interval is divided 
into m steps of length h, 
b a 
h 
m 
 

Euler’s Method 
 The main disadvantage of this method 
is that it is dependant on the step size 
m. Errors are greatly reduced if the 
step size is increased.
Example: Bacteria Growth 
 A colony of coliform bacteria is 
multiplying at the rate of r=0.8. If the 
initial count shows 1000 colonies, 
determine how many colonies exists in 
10 hours.
Solution 
 Defining: 
 N as the colony size. 
 r as the growth rate. 
 t as the time. 
 The rate equation can be given as: 
 rN N(0) 1000 
dN 
dt
 Numerical solution by applying Euler’s 
Algorithm: 
i i i N  N  h rN 1 
 Analytical solution; an approximate of the 
exact solution: 
rt N(t)  N(0) e
Solving by Euler’s method in 
MATLAB 
 The following code can be used to solve 
using Euler’s method and to compare with 
the exact solution for error observation: 
 h=0.5; %defining the interval length 
 r=0.8; 
 a=0; 
 b=10; 
 m=(b-a)/h; %estimating the number of 
steps 
 N(1)=1000; %N(0)
Euler’s code (cont) 
 t=a:h:b; %defining the interval with the 
step h 
 for i=1:m 
 N(i+1)=N(i)+r*h*N(i); %applying Euler's 
estimation 
 end 
 Nex=N(1)*exp(r*t); %calculating the 
exact answer from the analytical 
solution 
 disp([t' N' Nex']) 
 plot(t,N),xlabel('Hr'),ylabel('Bacteria'),
 Notice the huge error between the 
numerical and the analytical solution. 
The error can be reduced by reducing 
h of the numerical solution.
ODE built-in solvers in 
MATLAB 
 ODE built in solvers depend on the 
type and complexity of the system 
being solved and the accuracy 
needed. 
 The frequently used solvers are the 
ode23 and ode45 referring to 
second/third order and fourth/fifth 
order truncations of the tailor series 
respectively.
 To use these solvers a number of easy 
steps must be clearly defined to MATLAB: 
1. Create a function in an m file to define the 
right hand side of the equation to be 
solved. 
2. Determine the interval length for the 
independent variable or tspan vector 
3. Enter the initial conditions n0.
4. Call the solver to obtain the solution by 
typing the following command 
[t,y]=ode23(@functionName, tspan, n0) 
 The left hand side of the above expression 
is the output argument containing two 
vectors; t the independent variable and y the 
dependant variable. Other solvers use 
similar syntax.
Example: Bacteria Growth- 
Solving a first order equation 
 Define the function in an m file called 
bacrate.m 
 function y=f(t,N) 
 y=0.8*N; 
 In another m-file or in command 
window type the following:
 a=0; 
 b=10; 
 n0=1000; %N(0) 
 tspan=[a b]; % defining the interval of 
integration 
 [t,N]=ode23(@bacrate, tspan, n0) 
 Nex=n0*exp(0.8*t); %calculating the exact 
answer from the analytical solution 
 disp([t' N' Nex'])
 plot(t,N,'*'),xlabel('Hr'),ylabel('Bacteria') 
, title('Bacteria Growth') 
 hold on 
 plot(t,Nex,'r'),hold off
Second order equations 
 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. 
 Suppose y1 (x), y1 
’ (x), & y1 
’’ (x) are 
functions of x and y.
 Setting these equations into a first 
order system and defining initial 
conditions: 
y(x)= y(x) y(0)=a 
1y’(x)=y(x), and y’(0)=b 
2 y’’(x)=y’ (x) 
2 
 The second step is to enter the 
derivative equations as column vectors 
in MATLAB, then call the solver to 
obtain the solution.
Example 
 Solve the following second order ODE 
using ode45 solver: 
y  y  y  et '' ' 3 
 At y(0) = 2 and t at the range 
y'(0) = 4 0 to 5 
Then plot t versus y.
Step 1-Set to a 1st order ODE 
 Set y=y1 
 y’=y2 
 y’’=y2 
’ 
 This results in the following system: 
y  
y 
y  y  y  
et 
Rearranging: 
2 1 
' 
2 
2 
' 
1 
3 
2 
y ' 
 e t  3y  y y ' 
 
y 2 2 1 1
Step 2: Create m-files 
 In an m-file enter the derivative 
equations as a column vector and 
save it: 
 function dy=secondode(t,y) 
dy=[y(2);exp(t)-3*y(2)+y(1)];
 In the command window call the 
solver: 
 [t,y]=ode45('secondode',[0,5],[2,4]); % 
having tspan=[0 5] and initial 
conditions y(0)=2, y’(0)=4 
 plot(t,y)
0 0.5 1 1.5 2 2.5 3 3.5 4 4.5 5 
70 
60 
50 
40 
30 
20 
10 
0
EXERCISES 
 A fluid of constant density starts to flow 
into an empty and infinitely large tank 
at 8 L/s. A valve regulates the outlet 
flow to a constant 4L/s. Derive and 
solve the differential equation 
describing this process over a 100 
second interval.
Solving systems of ODEs 
 Systems of ODEs can be entered in an 
m-file using the same procedure of 2nd 
order ODE, however the initial values 
are entered as a row vector. 
 System of 1st oder ODEs will be 
discussed in this tutorial.
Solving systems of ODEs 
 Solve the following system: 
224 
   
10 10 
   
8 
    
dx 
dy 
dz 
At x(0)=-8, y(0)=8, z(0)=27, then plot z 
versus x. 
3 
3 
z xy 
dt 
y xz 
dt 
x y 
dt
Solution 
 Set x as g(1) 
 y as g(2) 
 z as g(3) 
 Then enter the ODEs in an m-file: 
 function dg= lorenz(t,g) 
 dg=[-10*g(1) + 10*g(2); -g(2) - g(1)*g(3); - 
8/3*g(3) + g(1)*g(2) – 224/3];
 In the command window type: 
 >>tspan=[0,50]; 
 >>g0=[-8;8;27]; 
 >>[t,g]=ode45(@lorenz,tspan,g0); 
 >>plot(g(:,1),g(:,3))
30 
20 
10 
0 
-10 
-20 
-30 
Z versus g 
-20 -15 -10 -5 0 5 10 15 20 
g 
z
Stiffness 
 ODEs methods discussed use a step 
value h over a given interval to 
estimate a numerical solution for the 
ode. 
 For some odes even such solvers 
would require a very small 
(infinitesimal) step value to converge. 
Such equations are called “stiff”.
 MATLAB has built-in solvers to deal 
with stiff odes such as ode15s, 
ode23s. 
 For a system of odes stiffness may 
also occur if one or more of the 
equations is converging too fast while 
another equation (or more) is 
converging too slowly.
Passing Additional Parameters 
 Letter parameters can be written to 
generalize the model represented by 
odes. Consider the system: 
having 
x(0)=105 
y(0)=8 
p=0.4, q=0.04 
r=0.02, s=2 
  
rxy sy 
dx 
dy 
dt 
px qxy 
dt 
 
 Create an m-file by entering the ODEs: 
 function dx=ques(t,x,p,q,r,s) 
 dx=[p*x(1)-q*x(1)*x(2); r*x(1)*x(2)- 
s*x(2)]; 
 In another mfile or in the command 
window type the following 
 p=0.4;q=0.04;r=0.02;s=2; 
 tspan=[0 10];
 X0=[105;8]; 
 [t,x]=ode23(@ques,tspan,X0,[],p,q,r,s); 
 plot(t,x) 
 xlabel('t') 
 ylabel('x,y')
0 1 2 3 4 5 6 7 8 9 10 
120 
100 
80 
60 
40 
20 
0 
t 
x,y
 Note that the term [] have been used. 
The reason being the more general 
format of calling a solver: 
 [t,x]=solver(handle, tspan, initial 
conditions, options, additional 
parameters) 
 When using additional parameters, the 
above format must be used and 
‘options’ can’t be omitted.
 Using ‘[]’ will tell MATLAB to hold the 
place for the options parameter, but 
since nothing has been defined; the 
default MATLAB options will be used 
to obtain the solution.

Weitere ähnliche Inhalte

Was ist angesagt?

Partial Differential Equations, 3 simple examples
Partial Differential Equations, 3 simple examplesPartial Differential Equations, 3 simple examples
Partial Differential Equations, 3 simple examplesEnrique Valderrama
 
linear transformation
linear transformationlinear transformation
linear transformationmansi acharya
 
Differential equations
Differential equationsDifferential equations
Differential equationsUzair Saiyed
 
Systems Of Differential Equations
Systems Of Differential EquationsSystems Of Differential Equations
Systems Of Differential EquationsJDagenais
 
08 interpolation lagrange
08 interpolation   lagrange08 interpolation   lagrange
08 interpolation lagrangeMohammad Tawfik
 
Presentation on Numerical Method (Trapezoidal Method)
Presentation on Numerical Method (Trapezoidal Method)Presentation on Numerical Method (Trapezoidal Method)
Presentation on Numerical Method (Trapezoidal Method)Syed Ahmed Zaki
 
Presentation on Solution to non linear equations
Presentation on Solution to non linear equationsPresentation on Solution to non linear equations
Presentation on Solution to non linear equationsRifat Rahamatullah
 
Engineering Mathematics-IV_B.Tech_Semester-IV_Unit-I
Engineering Mathematics-IV_B.Tech_Semester-IV_Unit-IEngineering Mathematics-IV_B.Tech_Semester-IV_Unit-I
Engineering Mathematics-IV_B.Tech_Semester-IV_Unit-IRai University
 
Newton’s Divided Difference Formula
Newton’s Divided Difference FormulaNewton’s Divided Difference Formula
Newton’s Divided Difference FormulaJas Singh Bhasin
 
Fourier Transform
Fourier TransformFourier Transform
Fourier TransformAamir Saeed
 
Series solution to ordinary differential equations
Series solution to ordinary differential equations Series solution to ordinary differential equations
Series solution to ordinary differential equations University of Windsor
 
Numerical Solution of Ordinary Differential Equations
Numerical Solution of Ordinary Differential EquationsNumerical Solution of Ordinary Differential Equations
Numerical Solution of Ordinary Differential EquationsMeenakshisundaram N
 
Runge-Kutta methods with examples
Runge-Kutta methods with examplesRunge-Kutta methods with examples
Runge-Kutta methods with examplesSajjad Hossain
 
Trapezoidal Method IN Numerical Analysis
Trapezoidal Method IN  Numerical AnalysisTrapezoidal Method IN  Numerical Analysis
Trapezoidal Method IN Numerical AnalysisMostafijur Rahman
 
first order ode with its application
 first order ode with its application first order ode with its application
first order ode with its applicationKrishna Peshivadiya
 

Was ist angesagt? (20)

Partial Differential Equations, 3 simple examples
Partial Differential Equations, 3 simple examplesPartial Differential Equations, 3 simple examples
Partial Differential Equations, 3 simple examples
 
linear transformation
linear transformationlinear transformation
linear transformation
 
Differential equations
Differential equationsDifferential equations
Differential equations
 
Power series
Power seriesPower series
Power series
 
Mean Value Theorems
Mean Value TheoremsMean Value Theorems
Mean Value Theorems
 
Interpolation
InterpolationInterpolation
Interpolation
 
Systems Of Differential Equations
Systems Of Differential EquationsSystems Of Differential Equations
Systems Of Differential Equations
 
08 interpolation lagrange
08 interpolation   lagrange08 interpolation   lagrange
08 interpolation lagrange
 
Presentation on Numerical Method (Trapezoidal Method)
Presentation on Numerical Method (Trapezoidal Method)Presentation on Numerical Method (Trapezoidal Method)
Presentation on Numerical Method (Trapezoidal Method)
 
Inverse laplace transforms
Inverse laplace transformsInverse laplace transforms
Inverse laplace transforms
 
Presentation on Solution to non linear equations
Presentation on Solution to non linear equationsPresentation on Solution to non linear equations
Presentation on Solution to non linear equations
 
Engineering Mathematics-IV_B.Tech_Semester-IV_Unit-I
Engineering Mathematics-IV_B.Tech_Semester-IV_Unit-IEngineering Mathematics-IV_B.Tech_Semester-IV_Unit-I
Engineering Mathematics-IV_B.Tech_Semester-IV_Unit-I
 
Laplace transforms
Laplace transformsLaplace transforms
Laplace transforms
 
Newton’s Divided Difference Formula
Newton’s Divided Difference FormulaNewton’s Divided Difference Formula
Newton’s Divided Difference Formula
 
Fourier Transform
Fourier TransformFourier Transform
Fourier Transform
 
Series solution to ordinary differential equations
Series solution to ordinary differential equations Series solution to ordinary differential equations
Series solution to ordinary differential equations
 
Numerical Solution of Ordinary Differential Equations
Numerical Solution of Ordinary Differential EquationsNumerical Solution of Ordinary Differential Equations
Numerical Solution of Ordinary Differential Equations
 
Runge-Kutta methods with examples
Runge-Kutta methods with examplesRunge-Kutta methods with examples
Runge-Kutta methods with examples
 
Trapezoidal Method IN Numerical Analysis
Trapezoidal Method IN  Numerical AnalysisTrapezoidal Method IN  Numerical Analysis
Trapezoidal Method IN Numerical Analysis
 
first order ode with its application
 first order ode with its application first order ode with its application
first order ode with its application
 

Andere mochten auch

Ordinary differential equations
Ordinary differential equationsOrdinary differential equations
Ordinary differential equationsAhmed Haider
 
Fragility analysis of open ground storey rc building designed using various m...
Fragility analysis of open ground storey rc building designed using various m...Fragility analysis of open ground storey rc building designed using various m...
Fragility analysis of open ground storey rc building designed using various m...eSAT Journals
 
FORTE-Seismic risk assessment of industrial plants a case study-ID1277-IDRC20...
FORTE-Seismic risk assessment of industrial plants a case study-ID1277-IDRC20...FORTE-Seismic risk assessment of industrial plants a case study-ID1277-IDRC20...
FORTE-Seismic risk assessment of industrial plants a case study-ID1277-IDRC20...Global Risk Forum GRFDavos
 
Advantages and Disadvantages of Using MATLAB/ode45 for Solving Differential E...
Advantages and Disadvantages of Using MATLAB/ode45 for Solving Differential E...Advantages and Disadvantages of Using MATLAB/ode45 for Solving Differential E...
Advantages and Disadvantages of Using MATLAB/ode45 for Solving Differential E...CSCJournals
 
Optics Fourier Transform Ii
Optics Fourier Transform IiOptics Fourier Transform Ii
Optics Fourier Transform Iidiarmseven
 
Risks projects - Hazard Maps - Honduras
Risks projects - Hazard Maps - HondurasRisks projects - Hazard Maps - Honduras
Risks projects - Hazard Maps - HondurasDavid Gutierrez Rivera
 
vector application
vector applicationvector application
vector applicationrajat shukla
 
Ch 04 MATLAB Applications in Chemical Engineering_陳奇中教授教學投影片
Ch 04 MATLAB Applications in Chemical Engineering_陳奇中教授教學投影片Ch 04 MATLAB Applications in Chemical Engineering_陳奇中教授教學投影片
Ch 04 MATLAB Applications in Chemical Engineering_陳奇中教授教學投影片Chyi-Tsong Chen
 
2015 Structures Congress - Probabilistic Performance Based Design
2015 Structures Congress - Probabilistic Performance Based Design2015 Structures Congress - Probabilistic Performance Based Design
2015 Structures Congress - Probabilistic Performance Based DesignGilsanz Murray Steficek
 
Application of coordinate system and vectors in the real life
Application of coordinate system and vectors in the real lifeApplication of coordinate system and vectors in the real life
Application of coordinate system and vectors in the real lifeАлиакбар Рахимов
 
Ode powerpoint presentation1
Ode powerpoint presentation1Ode powerpoint presentation1
Ode powerpoint presentation1Pokkarn Narkhede
 

Andere mochten auch (12)

Ordinary differential equations
Ordinary differential equationsOrdinary differential equations
Ordinary differential equations
 
Fragility analysis of open ground storey rc building designed using various m...
Fragility analysis of open ground storey rc building designed using various m...Fragility analysis of open ground storey rc building designed using various m...
Fragility analysis of open ground storey rc building designed using various m...
 
FORTE-Seismic risk assessment of industrial plants a case study-ID1277-IDRC20...
FORTE-Seismic risk assessment of industrial plants a case study-ID1277-IDRC20...FORTE-Seismic risk assessment of industrial plants a case study-ID1277-IDRC20...
FORTE-Seismic risk assessment of industrial plants a case study-ID1277-IDRC20...
 
Advantages and Disadvantages of Using MATLAB/ode45 for Solving Differential E...
Advantages and Disadvantages of Using MATLAB/ode45 for Solving Differential E...Advantages and Disadvantages of Using MATLAB/ode45 for Solving Differential E...
Advantages and Disadvantages of Using MATLAB/ode45 for Solving Differential E...
 
Optics Fourier Transform Ii
Optics Fourier Transform IiOptics Fourier Transform Ii
Optics Fourier Transform Ii
 
Risks projects - Hazard Maps - Honduras
Risks projects - Hazard Maps - HondurasRisks projects - Hazard Maps - Honduras
Risks projects - Hazard Maps - Honduras
 
vector application
vector applicationvector application
vector application
 
Ch 04 MATLAB Applications in Chemical Engineering_陳奇中教授教學投影片
Ch 04 MATLAB Applications in Chemical Engineering_陳奇中教授教學投影片Ch 04 MATLAB Applications in Chemical Engineering_陳奇中教授教學投影片
Ch 04 MATLAB Applications in Chemical Engineering_陳奇中教授教學投影片
 
SDEE: Lectures 3 and 4
SDEE: Lectures 3 and 4SDEE: Lectures 3 and 4
SDEE: Lectures 3 and 4
 
2015 Structures Congress - Probabilistic Performance Based Design
2015 Structures Congress - Probabilistic Performance Based Design2015 Structures Congress - Probabilistic Performance Based Design
2015 Structures Congress - Probabilistic Performance Based Design
 
Application of coordinate system and vectors in the real life
Application of coordinate system and vectors in the real lifeApplication of coordinate system and vectors in the real life
Application of coordinate system and vectors in the real life
 
Ode powerpoint presentation1
Ode powerpoint presentation1Ode powerpoint presentation1
Ode powerpoint presentation1
 

Ähnlich wie MATLAB ODE

from_data_to_differential_equations.ppt
from_data_to_differential_equations.pptfrom_data_to_differential_equations.ppt
from_data_to_differential_equations.pptashutoshvb1
 
MATLAB sessions Laboratory 3MAT 275 Laboratory 3Numeric.docx
MATLAB sessions Laboratory 3MAT 275 Laboratory 3Numeric.docxMATLAB sessions Laboratory 3MAT 275 Laboratory 3Numeric.docx
MATLAB sessions Laboratory 3MAT 275 Laboratory 3Numeric.docxandreecapon
 
DSP_FOEHU - MATLAB 01 - Discrete Time Signals and Systems
DSP_FOEHU - MATLAB 01 - Discrete Time Signals and SystemsDSP_FOEHU - MATLAB 01 - Discrete Time Signals and Systems
DSP_FOEHU - MATLAB 01 - Discrete Time Signals and SystemsAmr E. Mohamed
 
Tp problèmes-à-valeurs-initiales
Tp problèmes-à-valeurs-initialesTp problèmes-à-valeurs-initiales
Tp problèmes-à-valeurs-initialespapillontuba
 
MATLAB sessions Laboratory 4MAT 275 Laboratory 4MATLAB .docx
MATLAB sessions Laboratory 4MAT 275 Laboratory 4MATLAB .docxMATLAB sessions Laboratory 4MAT 275 Laboratory 4MATLAB .docx
MATLAB sessions Laboratory 4MAT 275 Laboratory 4MATLAB .docxandreecapon
 
Fault tolerant process control
Fault tolerant process controlFault tolerant process control
Fault tolerant process controlSpringer
 
The_variational_iteration_method_for_solving_linea.pdf
The_variational_iteration_method_for_solving_linea.pdfThe_variational_iteration_method_for_solving_linea.pdf
The_variational_iteration_method_for_solving_linea.pdfP Ramana
 
Ch 05 MATLAB Applications in Chemical Engineering_陳奇中教授教學投影片
Ch 05 MATLAB Applications in Chemical Engineering_陳奇中教授教學投影片Ch 05 MATLAB Applications in Chemical Engineering_陳奇中教授教學投影片
Ch 05 MATLAB Applications in Chemical Engineering_陳奇中教授教學投影片Chyi-Tsong Chen
 
A current perspectives of corrected operator splitting (os) for systems
A current perspectives of corrected operator splitting (os) for systemsA current perspectives of corrected operator splitting (os) for systems
A current perspectives of corrected operator splitting (os) for systemsAlexander Decker
 
Use the same variable names and write the function F - Force(x-ks-kc-l.pdf
Use the same variable names and write the function F - Force(x-ks-kc-l.pdfUse the same variable names and write the function F - Force(x-ks-kc-l.pdf
Use the same variable names and write the function F - Force(x-ks-kc-l.pdfacteleshoppe
 
SAMPLE QUESTIONExercise 1 Consider the functionf (x,C).docx
SAMPLE QUESTIONExercise 1 Consider the functionf (x,C).docxSAMPLE QUESTIONExercise 1 Consider the functionf (x,C).docx
SAMPLE QUESTIONExercise 1 Consider the functionf (x,C).docxanhlodge
 

Ähnlich wie MATLAB ODE (20)

from_data_to_differential_equations.ppt
from_data_to_differential_equations.pptfrom_data_to_differential_equations.ppt
from_data_to_differential_equations.ppt
 
Matlab lab.pdf
Matlab lab.pdfMatlab lab.pdf
Matlab lab.pdf
 
NPDE-TCA
NPDE-TCANPDE-TCA
NPDE-TCA
 
MATLAB sessions Laboratory 3MAT 275 Laboratory 3Numeric.docx
MATLAB sessions Laboratory 3MAT 275 Laboratory 3Numeric.docxMATLAB sessions Laboratory 3MAT 275 Laboratory 3Numeric.docx
MATLAB sessions Laboratory 3MAT 275 Laboratory 3Numeric.docx
 
Mechanical Engineering Assignment Help
Mechanical Engineering Assignment HelpMechanical Engineering Assignment Help
Mechanical Engineering Assignment Help
 
DSP_FOEHU - MATLAB 01 - Discrete Time Signals and Systems
DSP_FOEHU - MATLAB 01 - Discrete Time Signals and SystemsDSP_FOEHU - MATLAB 01 - Discrete Time Signals and Systems
DSP_FOEHU - MATLAB 01 - Discrete Time Signals and Systems
 
Signals And Systems Assignment Help
Signals And Systems Assignment HelpSignals And Systems Assignment Help
Signals And Systems Assignment Help
 
Tp problèmes-à-valeurs-initiales
Tp problèmes-à-valeurs-initialesTp problèmes-à-valeurs-initiales
Tp problèmes-à-valeurs-initiales
 
MATLAB sessions Laboratory 4MAT 275 Laboratory 4MATLAB .docx
MATLAB sessions Laboratory 4MAT 275 Laboratory 4MATLAB .docxMATLAB sessions Laboratory 4MAT 275 Laboratory 4MATLAB .docx
MATLAB sessions Laboratory 4MAT 275 Laboratory 4MATLAB .docx
 
Intro to modelling_wur
Intro to modelling_wurIntro to modelling_wur
Intro to modelling_wur
 
Ep 5512 lecture-02
Ep 5512 lecture-02Ep 5512 lecture-02
Ep 5512 lecture-02
 
Lsd ee n
Lsd ee nLsd ee n
Lsd ee n
 
Linear regression
Linear regressionLinear regression
Linear regression
 
Matlab Sample Assignment Solution
Matlab Sample Assignment SolutionMatlab Sample Assignment Solution
Matlab Sample Assignment Solution
 
Fault tolerant process control
Fault tolerant process controlFault tolerant process control
Fault tolerant process control
 
The_variational_iteration_method_for_solving_linea.pdf
The_variational_iteration_method_for_solving_linea.pdfThe_variational_iteration_method_for_solving_linea.pdf
The_variational_iteration_method_for_solving_linea.pdf
 
Ch 05 MATLAB Applications in Chemical Engineering_陳奇中教授教學投影片
Ch 05 MATLAB Applications in Chemical Engineering_陳奇中教授教學投影片Ch 05 MATLAB Applications in Chemical Engineering_陳奇中教授教學投影片
Ch 05 MATLAB Applications in Chemical Engineering_陳奇中教授教學投影片
 
A current perspectives of corrected operator splitting (os) for systems
A current perspectives of corrected operator splitting (os) for systemsA current perspectives of corrected operator splitting (os) for systems
A current perspectives of corrected operator splitting (os) for systems
 
Use the same variable names and write the function F - Force(x-ks-kc-l.pdf
Use the same variable names and write the function F - Force(x-ks-kc-l.pdfUse the same variable names and write the function F - Force(x-ks-kc-l.pdf
Use the same variable names and write the function F - Force(x-ks-kc-l.pdf
 
SAMPLE QUESTIONExercise 1 Consider the functionf (x,C).docx
SAMPLE QUESTIONExercise 1 Consider the functionf (x,C).docxSAMPLE QUESTIONExercise 1 Consider the functionf (x,C).docx
SAMPLE QUESTIONExercise 1 Consider the functionf (x,C).docx
 

Kürzlich hochgeladen

social pharmacy d-pharm 1st year by Pragati K. Mahajan
social pharmacy d-pharm 1st year by Pragati K. Mahajansocial pharmacy d-pharm 1st year by Pragati K. Mahajan
social pharmacy d-pharm 1st year by Pragati K. Mahajanpragatimahajan3
 
9548086042 for call girls in Indira Nagar with room service
9548086042  for call girls in Indira Nagar  with room service9548086042  for call girls in Indira Nagar  with room service
9548086042 for call girls in Indira Nagar with room servicediscovermytutordmt
 
Ecosystem Interactions Class Discussion Presentation in Blue Green Lined Styl...
Ecosystem Interactions Class Discussion Presentation in Blue Green Lined Styl...Ecosystem Interactions Class Discussion Presentation in Blue Green Lined Styl...
Ecosystem Interactions Class Discussion Presentation in Blue Green Lined Styl...fonyou31
 
1029 - Danh muc Sach Giao Khoa 10 . pdf
1029 -  Danh muc Sach Giao Khoa 10 . pdf1029 -  Danh muc Sach Giao Khoa 10 . pdf
1029 - Danh muc Sach Giao Khoa 10 . pdfQucHHunhnh
 
SOCIAL AND HISTORICAL CONTEXT - LFTVD.pptx
SOCIAL AND HISTORICAL CONTEXT - LFTVD.pptxSOCIAL AND HISTORICAL CONTEXT - LFTVD.pptx
SOCIAL AND HISTORICAL CONTEXT - LFTVD.pptxiammrhaywood
 
1029-Danh muc Sach Giao Khoa khoi 6.pdf
1029-Danh muc Sach Giao Khoa khoi  6.pdf1029-Danh muc Sach Giao Khoa khoi  6.pdf
1029-Danh muc Sach Giao Khoa khoi 6.pdfQucHHunhnh
 
Beyond the EU: DORA and NIS 2 Directive's Global Impact
Beyond the EU: DORA and NIS 2 Directive's Global ImpactBeyond the EU: DORA and NIS 2 Directive's Global Impact
Beyond the EU: DORA and NIS 2 Directive's Global ImpactPECB
 
Mastering the Unannounced Regulatory Inspection
Mastering the Unannounced Regulatory InspectionMastering the Unannounced Regulatory Inspection
Mastering the Unannounced Regulatory InspectionSafetyChain Software
 
Nutritional Needs Presentation - HLTH 104
Nutritional Needs Presentation - HLTH 104Nutritional Needs Presentation - HLTH 104
Nutritional Needs Presentation - HLTH 104misteraugie
 
microwave assisted reaction. General introduction
microwave assisted reaction. General introductionmicrowave assisted reaction. General introduction
microwave assisted reaction. General introductionMaksud Ahmed
 
Web & Social Media Analytics Previous Year Question Paper.pdf
Web & Social Media Analytics Previous Year Question Paper.pdfWeb & Social Media Analytics Previous Year Question Paper.pdf
Web & Social Media Analytics Previous Year Question Paper.pdfJayanti Pande
 
Call Girls in Dwarka Mor Delhi Contact Us 9654467111
Call Girls in Dwarka Mor Delhi Contact Us 9654467111Call Girls in Dwarka Mor Delhi Contact Us 9654467111
Call Girls in Dwarka Mor Delhi Contact Us 9654467111Sapana Sha
 
Measures of Central Tendency: Mean, Median and Mode
Measures of Central Tendency: Mean, Median and ModeMeasures of Central Tendency: Mean, Median and Mode
Measures of Central Tendency: Mean, Median and ModeThiyagu K
 
Organic Name Reactions for the students and aspirants of Chemistry12th.pptx
Organic Name Reactions  for the students and aspirants of Chemistry12th.pptxOrganic Name Reactions  for the students and aspirants of Chemistry12th.pptx
Organic Name Reactions for the students and aspirants of Chemistry12th.pptxVS Mahajan Coaching Centre
 
Sports & Fitness Value Added Course FY..
Sports & Fitness Value Added Course FY..Sports & Fitness Value Added Course FY..
Sports & Fitness Value Added Course FY..Disha Kariya
 
mini mental status format.docx
mini    mental       status     format.docxmini    mental       status     format.docx
mini mental status format.docxPoojaSen20
 
Software Engineering Methodologies (overview)
Software Engineering Methodologies (overview)Software Engineering Methodologies (overview)
Software Engineering Methodologies (overview)eniolaolutunde
 

Kürzlich hochgeladen (20)

social pharmacy d-pharm 1st year by Pragati K. Mahajan
social pharmacy d-pharm 1st year by Pragati K. Mahajansocial pharmacy d-pharm 1st year by Pragati K. Mahajan
social pharmacy d-pharm 1st year by Pragati K. Mahajan
 
9548086042 for call girls in Indira Nagar with room service
9548086042  for call girls in Indira Nagar  with room service9548086042  for call girls in Indira Nagar  with room service
9548086042 for call girls in Indira Nagar with room service
 
Ecosystem Interactions Class Discussion Presentation in Blue Green Lined Styl...
Ecosystem Interactions Class Discussion Presentation in Blue Green Lined Styl...Ecosystem Interactions Class Discussion Presentation in Blue Green Lined Styl...
Ecosystem Interactions Class Discussion Presentation in Blue Green Lined Styl...
 
1029 - Danh muc Sach Giao Khoa 10 . pdf
1029 -  Danh muc Sach Giao Khoa 10 . pdf1029 -  Danh muc Sach Giao Khoa 10 . pdf
1029 - Danh muc Sach Giao Khoa 10 . pdf
 
SOCIAL AND HISTORICAL CONTEXT - LFTVD.pptx
SOCIAL AND HISTORICAL CONTEXT - LFTVD.pptxSOCIAL AND HISTORICAL CONTEXT - LFTVD.pptx
SOCIAL AND HISTORICAL CONTEXT - LFTVD.pptx
 
1029-Danh muc Sach Giao Khoa khoi 6.pdf
1029-Danh muc Sach Giao Khoa khoi  6.pdf1029-Danh muc Sach Giao Khoa khoi  6.pdf
1029-Danh muc Sach Giao Khoa khoi 6.pdf
 
INDIA QUIZ 2024 RLAC DELHI UNIVERSITY.pptx
INDIA QUIZ 2024 RLAC DELHI UNIVERSITY.pptxINDIA QUIZ 2024 RLAC DELHI UNIVERSITY.pptx
INDIA QUIZ 2024 RLAC DELHI UNIVERSITY.pptx
 
Beyond the EU: DORA and NIS 2 Directive's Global Impact
Beyond the EU: DORA and NIS 2 Directive's Global ImpactBeyond the EU: DORA and NIS 2 Directive's Global Impact
Beyond the EU: DORA and NIS 2 Directive's Global Impact
 
Mastering the Unannounced Regulatory Inspection
Mastering the Unannounced Regulatory InspectionMastering the Unannounced Regulatory Inspection
Mastering the Unannounced Regulatory Inspection
 
Nutritional Needs Presentation - HLTH 104
Nutritional Needs Presentation - HLTH 104Nutritional Needs Presentation - HLTH 104
Nutritional Needs Presentation - HLTH 104
 
microwave assisted reaction. General introduction
microwave assisted reaction. General introductionmicrowave assisted reaction. General introduction
microwave assisted reaction. General introduction
 
Advance Mobile Application Development class 07
Advance Mobile Application Development class 07Advance Mobile Application Development class 07
Advance Mobile Application Development class 07
 
Web & Social Media Analytics Previous Year Question Paper.pdf
Web & Social Media Analytics Previous Year Question Paper.pdfWeb & Social Media Analytics Previous Year Question Paper.pdf
Web & Social Media Analytics Previous Year Question Paper.pdf
 
Mattingly "AI & Prompt Design: The Basics of Prompt Design"
Mattingly "AI & Prompt Design: The Basics of Prompt Design"Mattingly "AI & Prompt Design: The Basics of Prompt Design"
Mattingly "AI & Prompt Design: The Basics of Prompt Design"
 
Call Girls in Dwarka Mor Delhi Contact Us 9654467111
Call Girls in Dwarka Mor Delhi Contact Us 9654467111Call Girls in Dwarka Mor Delhi Contact Us 9654467111
Call Girls in Dwarka Mor Delhi Contact Us 9654467111
 
Measures of Central Tendency: Mean, Median and Mode
Measures of Central Tendency: Mean, Median and ModeMeasures of Central Tendency: Mean, Median and Mode
Measures of Central Tendency: Mean, Median and Mode
 
Organic Name Reactions for the students and aspirants of Chemistry12th.pptx
Organic Name Reactions  for the students and aspirants of Chemistry12th.pptxOrganic Name Reactions  for the students and aspirants of Chemistry12th.pptx
Organic Name Reactions for the students and aspirants of Chemistry12th.pptx
 
Sports & Fitness Value Added Course FY..
Sports & Fitness Value Added Course FY..Sports & Fitness Value Added Course FY..
Sports & Fitness Value Added Course FY..
 
mini mental status format.docx
mini    mental       status     format.docxmini    mental       status     format.docx
mini mental status format.docx
 
Software Engineering Methodologies (overview)
Software Engineering Methodologies (overview)Software Engineering Methodologies (overview)
Software Engineering Methodologies (overview)
 

MATLAB ODE

  • 1. Using ODEs in MATLAB Prepared By: Nahla Al Amoodi 17th September 2007
  • 2. ODEs  The initial value problem for an ordinary differential equation involves finding a function y(t) that satisfies: With the initial condition y(t0)=y0 A numerical solution generates a sequence of values for the independent variable, and a corresponding sequence of values for the dependent variable, such that each yn approximates the solution at tn.
  • 3. Euler’s Method  Works mainly for simple first order differential equations.  Consider the following equation: and y(0) given f (x, y) dy dx   This differential can be replaced with its Newton quotient:
  • 4. Euler’s Method ( , ) y x h y x ( ) ( ) f x y h    Rearranging: y(x  h)  y(x)  hf (x, y)    (1) Developing an iterative scheme: ( , ) i 1 i i i y  y  hf x y  Where ( ) i i y  y x
  • 5. Euler’s Method Where ( ) i i y  y x  such that at the beginning of step i, ( 1) (0) 1 x i h and y y i    Suppose that the ode is to be integrated over the interval from x=a to x=b. This interval is divided into m steps of length h, b a h m  
  • 6. Euler’s Method  The main disadvantage of this method is that it is dependant on the step size m. Errors are greatly reduced if the step size is increased.
  • 7. Example: Bacteria Growth  A colony of coliform bacteria is multiplying at the rate of r=0.8. If the initial count shows 1000 colonies, determine how many colonies exists in 10 hours.
  • 8. Solution  Defining:  N as the colony size.  r as the growth rate.  t as the time.  The rate equation can be given as:  rN N(0) 1000 dN dt
  • 9.  Numerical solution by applying Euler’s Algorithm: i i i N  N  h rN 1  Analytical solution; an approximate of the exact solution: rt N(t)  N(0) e
  • 10. Solving by Euler’s method in MATLAB  The following code can be used to solve using Euler’s method and to compare with the exact solution for error observation:  h=0.5; %defining the interval length  r=0.8;  a=0;  b=10;  m=(b-a)/h; %estimating the number of steps  N(1)=1000; %N(0)
  • 11. Euler’s code (cont)  t=a:h:b; %defining the interval with the step h  for i=1:m  N(i+1)=N(i)+r*h*N(i); %applying Euler's estimation  end  Nex=N(1)*exp(r*t); %calculating the exact answer from the analytical solution  disp([t' N' Nex'])  plot(t,N),xlabel('Hr'),ylabel('Bacteria'),
  • 12.
  • 13.  Notice the huge error between the numerical and the analytical solution. The error can be reduced by reducing h of the numerical solution.
  • 14. ODE built-in solvers in MATLAB  ODE built in solvers depend on the type and complexity of the system being solved and the accuracy needed.  The frequently used solvers are the ode23 and ode45 referring to second/third order and fourth/fifth order truncations of the tailor series respectively.
  • 15.  To use these solvers a number of easy steps must be clearly defined to MATLAB: 1. Create a function in an m file to define the right hand side of the equation to be solved. 2. Determine the interval length for the independent variable or tspan vector 3. Enter the initial conditions n0.
  • 16. 4. Call the solver to obtain the solution by typing the following command [t,y]=ode23(@functionName, tspan, n0)  The left hand side of the above expression is the output argument containing two vectors; t the independent variable and y the dependant variable. Other solvers use similar syntax.
  • 17. Example: Bacteria Growth- Solving a first order equation  Define the function in an m file called bacrate.m  function y=f(t,N)  y=0.8*N;  In another m-file or in command window type the following:
  • 18.  a=0;  b=10;  n0=1000; %N(0)  tspan=[a b]; % defining the interval of integration  [t,N]=ode23(@bacrate, tspan, n0)  Nex=n0*exp(0.8*t); %calculating the exact answer from the analytical solution  disp([t' N' Nex'])
  • 19.  plot(t,N,'*'),xlabel('Hr'),ylabel('Bacteria') , title('Bacteria Growth')  hold on  plot(t,Nex,'r'),hold off
  • 20.
  • 21. Second order equations  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.  Suppose y1 (x), y1 ’ (x), & y1 ’’ (x) are functions of x and y.
  • 22.  Setting these equations into a first order system and defining initial conditions: y(x)= y(x) y(0)=a 1y’(x)=y(x), and y’(0)=b 2 y’’(x)=y’ (x) 2  The second step is to enter the derivative equations as column vectors in MATLAB, then call the solver to obtain the solution.
  • 23. Example  Solve the following second order ODE using ode45 solver: y  y  y  et '' ' 3  At y(0) = 2 and t at the range y'(0) = 4 0 to 5 Then plot t versus y.
  • 24. Step 1-Set to a 1st order ODE  Set y=y1  y’=y2  y’’=y2 ’  This results in the following system: y  y y  y  y  et Rearranging: 2 1 ' 2 2 ' 1 3 2 y '  e t  3y  y y '  y 2 2 1 1
  • 25. Step 2: Create m-files  In an m-file enter the derivative equations as a column vector and save it:  function dy=secondode(t,y) dy=[y(2);exp(t)-3*y(2)+y(1)];
  • 26.  In the command window call the solver:  [t,y]=ode45('secondode',[0,5],[2,4]); % having tspan=[0 5] and initial conditions y(0)=2, y’(0)=4  plot(t,y)
  • 27. 0 0.5 1 1.5 2 2.5 3 3.5 4 4.5 5 70 60 50 40 30 20 10 0
  • 28. EXERCISES  A fluid of constant density starts to flow into an empty and infinitely large tank at 8 L/s. A valve regulates the outlet flow to a constant 4L/s. Derive and solve the differential equation describing this process over a 100 second interval.
  • 29.
  • 30. Solving systems of ODEs  Systems of ODEs can be entered in an m-file using the same procedure of 2nd order ODE, however the initial values are entered as a row vector.  System of 1st oder ODEs will be discussed in this tutorial.
  • 31. Solving systems of ODEs  Solve the following system: 224    10 10    8     dx dy dz At x(0)=-8, y(0)=8, z(0)=27, then plot z versus x. 3 3 z xy dt y xz dt x y dt
  • 32. Solution  Set x as g(1)  y as g(2)  z as g(3)  Then enter the ODEs in an m-file:  function dg= lorenz(t,g)  dg=[-10*g(1) + 10*g(2); -g(2) - g(1)*g(3); - 8/3*g(3) + g(1)*g(2) – 224/3];
  • 33.  In the command window type:  >>tspan=[0,50];  >>g0=[-8;8;27];  >>[t,g]=ode45(@lorenz,tspan,g0);  >>plot(g(:,1),g(:,3))
  • 34. 30 20 10 0 -10 -20 -30 Z versus g -20 -15 -10 -5 0 5 10 15 20 g z
  • 35. Stiffness  ODEs methods discussed use a step value h over a given interval to estimate a numerical solution for the ode.  For some odes even such solvers would require a very small (infinitesimal) step value to converge. Such equations are called “stiff”.
  • 36.  MATLAB has built-in solvers to deal with stiff odes such as ode15s, ode23s.  For a system of odes stiffness may also occur if one or more of the equations is converging too fast while another equation (or more) is converging too slowly.
  • 37. Passing Additional Parameters  Letter parameters can be written to generalize the model represented by odes. Consider the system: having x(0)=105 y(0)=8 p=0.4, q=0.04 r=0.02, s=2   rxy sy dx dy dt px qxy dt  
  • 38.  Create an m-file by entering the ODEs:  function dx=ques(t,x,p,q,r,s)  dx=[p*x(1)-q*x(1)*x(2); r*x(1)*x(2)- s*x(2)];  In another mfile or in the command window type the following  p=0.4;q=0.04;r=0.02;s=2;  tspan=[0 10];
  • 39.  X0=[105;8];  [t,x]=ode23(@ques,tspan,X0,[],p,q,r,s);  plot(t,x)  xlabel('t')  ylabel('x,y')
  • 40. 0 1 2 3 4 5 6 7 8 9 10 120 100 80 60 40 20 0 t x,y
  • 41.  Note that the term [] have been used. The reason being the more general format of calling a solver:  [t,x]=solver(handle, tspan, initial conditions, options, additional parameters)  When using additional parameters, the above format must be used and ‘options’ can’t be omitted.
  • 42.  Using ‘[]’ will tell MATLAB to hold the place for the options parameter, but since nothing has been defined; the default MATLAB options will be used to obtain the solution.