0% found this document useful (0 votes)
9 views34 pages

MME 208 Lecture-7 ODE

math lab

Uploaded by

Samiul Karim Sk
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
9 views34 pages

MME 208 Lecture-7 ODE

math lab

Uploaded by

Samiul Karim Sk
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 34

MME 208- Computer Applications to Materials Engineering

Numerical Techniques:
ODE and PDE

Course Instructors: Humayun Kabir , Sumit Bhowmick , Md. Nazmul Ahsan Dipon
Lecturer, MME

Bangladesh University of Engineering and Technology- BUET 1


2

Part – I
Ordinary Differential
Equation (ODE)
ODE- Operators
• Have your symbolic math toolbox installed!
• syms -- Create symbolic scalar variables and functions, and matrix variables and functions

• diff – The basic differential operator, i.e. diff(y,t,2) means


• Can be used for ODE solving as well

• dsolve – solves the ODE as formed by expression made of dsolve


• Can incorporate boundary conditions and implicit solutions also
3
ODE-Analytic Solution
• For a ‘simple’ Third-order ODE

write the code!

• syms y(t) a b c % function and const. declared


• eqn = diff(y,t,3)- 2*diff(y)+a*y+b*t+c==0;
• % diff(y) is same as diff(y,t,1)
• S = dsolve(eqn) % (or any other suitable name instead of just S )

• And we have the results!


• S =
C1*exp(a^(1/3)t) - c/a + C2*exp(-t((3^(1/2)a^(1/3)1i)/2 + a^(1/3)/2)) +
C3*exp(t((3^(1/2)a^(1/3)1i)/2 - a^(1/3)/2)) - (b*t)/a

4
ODE-Analytic Solution

• To find any suitable value for plotting, use S(a,b,c,t)(that is S as a function) on code
first and treat S as any other function for value extraction or plotting afterwards!
• But integration constants will create problems- you cannot evaluate numerical values then!
• From order of equation, you can guess beforehand how many integration constants are
coming. E.g. you know from 3rd order ODE, 3 integration constants would come

5
ODE-Implicit Solution
• Do this when you think you are getting no explicit/ analytic solution

• For The ODE = , write the code!


• syms y(x) a b c d
• eqn = diff(y) == (a*x+b*exp(x))/(c*y(x)+d*exp(y(x)));
• S = dsolve(eqn,'Implicit',true)

• And we have the results! (solve implicit equation by hand!)


• S =
(c*y(x)^2)/2 + d*exp(y(x)) == C1 + (a*x^2)/2 + b*exp(x)

6
ODE- implicit solution plotting
• Directly using fimplicit doesn’t work on expression of S where both LHS and RHS of == are
nonzero

1. First change the symbolic expression to character string using char()


2. Then change side of expression so that RHS becomes zero. You need to replace some
characters, use strrep() function for that purpose
𝑎𝑥 + sin 𝑦 == 𝑦 + 𝑏 sin 𝑥 → 𝑎𝑥 + sin 𝑦 − 𝑦 − 𝑏 sin 𝑥 == 0
3. Convert the string back to symbolic with str2sym() function
4. Assign suitable numerical values to LHS constants with subs() and
matlabFunction() so that can be fed to fimplicit
𝑎𝑥 + sin 𝑦 − 𝑦 − 𝑏 sin 𝑥 → 3𝑥 + sin 𝑦 − 𝑦 + 4 sin 𝑥

7
ODE-Implicit numerical Solution
% Define the symbolic variables and the implicit equation
syms y(x) a b c d C1 syms y(x) a b c d C1
eqn=diff(y,x)==(a*x+b*exp(x))/(c*y+d*exp(y));
s=dsolve(eqn,'implicit',true);
eqn = diff(y) == (a*x+b*exp(x))/(c*y(x)+d*exp(y(x))); s_str=char(s);
s_sm=strrep(s_str,'==','-(');
s_sm=strrep(s_sm,'y(x)','y');
S = dsolve(eqn,'Implicit',true); s_sm=[s_sm ')'];
s_mod = str2sym(s_sm);
s_num=subs(s_mod,[a,b,c,d,C1],[2,3,5,1,4]);
s_function=matlabFunction(s_num);
fimplicit(s_function,[-10,10,-10,10])

% Convert the symbolic expression to a string


S_str = char(S);

% Replace '==' with '-(' in the string, and 'y(x)' with 'y'
S_sm = strrep(S_str, '==', '-(');
S_sm = strrep(S_sm, 'y(x)', 'y');

% Add a single ')' at the end of the modified string


S_sm = [S_sm ')'];
8
ODE-Implicit numerical Solution
% Convert the modified string back to a symbolic
expression
S_mod = str2sym(S_sm);

% Substitute the numerical values for the other


variables using the `subs` function:
S_num = subs(S_mod, [a,b,c,d,C1],
[2,3,5,1,4]);
% Convert the symbolic expression to a function
handle using the `matlabFunction` function:
S_func = matlabFunction(S_num);
Some more complicated
% Use `fimplicit` to plot the equation implicitly function do not have even
% specified the desired ranges `[xmin, xmax, implicit solutions!
ymin, ymax]` for the plot. Only Numerical would be the
way
fimplicit(S_func, [-10,10,-10,10]); 9
ODE- Solution with Condition
• Add the conditions into the code!

• Say, +𝑎 + 𝑏𝑦 + 𝑐 = 0; 𝑦 0 = 𝐹; 𝑦 0 = 𝐸

• syms y(t) a b c E F
• eqn = diff(y,t,2)+a*(diff(y))+b*y+c==0;
• Dy=diff(y);
• cond = [y(0)==E Dy(0)==F];
• S = dsolve(eqn,cond)

10
ODE- Solution with Condition
• And we have the results!
• Write S(E,F,a,b,c,t) = dsolve(eqn,cond) instead of S =
dsolve(eqn,cond) to leverage the function!
• Find a few value from this solution.

• While we’ve got an explicit/analytic expression here, Remember, even implicit solutions
aren’t guaranteed for many expressions
• Series solution of some equations available, but beyond scope.

11
ODE-Multiple solutions
• Equations like + 𝐴𝑥 + 𝐵𝑦 = 0 has two valid solution. Let’s solve it!
• syms y(x) A B
• eqn = (diff(y))^2+(A*x+B*y)*diff(y)+A*B*x*y==0;
• S = dsolve(eqn)
• The solution Turns out to be clear,clc
syms y(x) a b
S = eqn=(diff(y)+a*x)*(diff(y)+b*x)==0;
s=dsolve(eqn)

C1*exp(-B*x)
C2 - (A*x^2)/2
Both are correct, the solution are shown vertically stacked.

12
Systems of ODE- an example inspiration
• Consider the following system of ordinary differential equations (ODEs) :
• 𝑑𝑦/𝑑𝑡 = 𝑎*y+𝑏*z
• 𝑑𝑧/𝑑𝑡 = c*z +d*y
• Consider these equations representing a reactive system, where y represents the concentration
of a reactant, and z represents the concentration of a product, mediated by a third active
medium/intermediate that can convert into either.
• The first equation represents the forward reaction, where the reactant (y) is consumed at a rate
proportional to the concentration of the product (z) and reactant (y)itself . The second equation
represents the backward reaction, similarly.
• Here a,b,c,d, can be either positive or negative
• The system exhibits a feedback mechanism, where the growth rate of y and z are influenced by
the concentration of both y and z.

13
Systems of ODE
• To solve = 𝑎𝑦 + 𝑏𝑧; = 𝑐𝑧 + 𝑑𝑦. We write
• syms y(t) z(t) a b c d
• eqns = [diff(y) == a*y+b*z, diff(z) == c*z+d*y];
• S = dsolve(eqns);s=[S.y;S.z]
• And we obtain (top row y, bottom row z, mind it!) s=

syms y(x) z(x) a b c d T E F


eqn=[diff(y)==a*y+b*z , diff(z)==c*z+d*y];

cond=[y(T)==E z(T)==F];
s=dsolve(eqn,cond);

14
Systems of ODE
• Let at time T, concentration of reactant is E and product is F
• Setting the condition cond=[y(T)==E,z(T)==F] and writing S =
dsolve(eqns,cond) instead of S = dsolve(eqns) provides explicit formulas for y
and z, that are too messy to be shown here. Here is compacted and cleaned-up version of these
two

𝑧
(𝐹𝑎 − 𝐹𝑐 − 2𝐸𝑑) (𝑇 − 𝑡) √𝑎2 − 2𝑎𝑐 + 𝑐 2 + 4𝑏𝑑 (𝑇 − 𝑡) √𝑎2 − 2𝑎𝑐 + 𝑐 2 + 4𝑏𝑑
cosh +𝐹 sinh
2 2 2 2
= √𝑎 − 2𝑎𝑐 + 𝑐 + 4𝑏𝑑
(𝑇 − 𝑡)(𝑎 + 𝑐)
exp
2
15
Systems of ODE- contd.
• Want to use y and z as custom function of t (and also a,b,c,d, T,E,F) without copying the
expressions for y and z?
• Writing S(t,a,b,c,d,T,E,F) or s(t,a,b,c,d,T,E,F) doesn’t work here. Then?
• Write these two small codes, marked here

>> syms y(t) z(t) a b c d T E F


eqns = [diff(y,t) == a*y+b*z,
syms y(t) z(t) a b c d T E F
diff(z,t) == c*z+d*y];
eqn=[diff(y,t)==a*y+b*z , diff(z,t)==c*z+d*y];

cond=[y(T)==E, z(T)==F];
s=dsolve(eqn,cond);
cond=[y(T)==E,z(T)==F];
S=[s.y;s.z];
sy= @(t, a, b, c, d, T, E, F) eval(s.y);
sz= @(t, a, b, c, d, T, E, F) eval(s.z);
S = dsolve(eqns,cond);s=[S.y;S.z];
sz(2,1,4,3,6,5,8,7)
sy = @(t,a,b,c,d,T,E,F) eval(S.y);
sz = @(t,a,b,c,d,T,E,F) eval(S.z);

16
Systems of ODE- contd.
sy = @(t,a,b,c,d,T,E,F) eval(S.y);
sz = @(t,a,b,c,d,T,E,F) eval(S.z);

sz(2,1,4,3,6,5,8,7)
ans =
-1.6206e+04

plot(-1:.01:1.2,...
sy(-1:.01:1.2,3,1,2,-4,5,-2,-1));

• Could use C1 and C2 instead of T,E,F too, then no condition would be required
• Systems of ODE cannot solve implicit ones!
• Let’s then go to numerical without any analytical expression!

17
Systems of ODE- Matrix Form
Without Initial Condition
>> syms x(t) y(t)
A = [1 2; -1 1];B = [1; t];
Y = [x; y];
odes = diff(Y) == A*Y + B;
[xSol(t),ySol(t)] = dsolve(odes);
xSol(t)= simplify(xSol(t))
ySol(t)= simplify(ySol(t))

• There can be functions of t in matrix A as well! 18


Systems of ODE- Matrix Form
With Initial Condition: At t=0, x=2,y=-1
>> syms x(t) y(t)
A = [1 2; -1 1]; B = [1; t];
Y = [x; y];
odes = diff(Y) == A*Y + B;
C = Y(0) == [2;-1];
[xSol(t),ySol(t)] = dsolve(odes,C);
xSol(t)= simplify(xSol(t))
ySol(t)= simplify(ySol(t))

2 𝑡 17 exp(𝑡) cos √2𝑡 7√2 exp(𝑡) sin √2𝑡 1


𝑥𝑆𝑜𝑙(𝑡) = + − +
3 9 9 9
𝑡 7 exp(𝑡) cos √2𝑡 17√2 exp(𝑡) sin √2𝑡 2
𝑦𝑆𝑜𝑙(𝑡) = − − − −
3 9 18 9
• There can be functions of t in matrix A as well! 19
Higher-order ODE to systems of ODE
• All higher-order ODEs can be split into 1st-order system of multiple ODEs; be it 2nd, 3rd …etc.
order; that we shall see later
• Simply mathematical manipulation
𝑦 + 3𝑦′′𝑦 + 3𝑦 𝑦 + 𝑦 = 0 →
𝑑𝑦 𝑑𝑦 𝑑𝑦
=𝑦 ; =𝑦 ; = −3𝑦 𝑦 − 3𝑦 𝑦 − 𝑦
𝑑𝑥 𝑑𝑥 𝑑𝑥
• Or use odeToVectorField function
• >> syms y(x)
odeToVectorField(diff(y,x,3)+3*diff(y,x,2)*y+3*diff(y)*y^2+y^3==0)
ans =
Here
Y[2] =d/dx Y[1] y→Y[1]
Y[3] =d/dx Y[2] ya→Y[2]
-Y[1]^3-3Y[2]Y[1]^2-3Y[3]Y[1] =d/dx Y[3] yb→Y[3] 20
Solving ODE Numerically
• ODE numerical solution means discretizing the space and using techniques like finite-
difference, Runge-Kutta etc. there for approximation
• MATLAB ODE solvers have built-in functions for implementation of these techniques.

• Different algorithm suits for different levels of speed and accuracy of ODE, so multiple ODE
solvers in MATLAB- no fixed choice of solvers there

• Stiff and Non-stiff differential equations w.r.t. numerical stability of Differential equations.
• Not a strict definition, but, if using simpler algorithms to solve the ODE causes solution to
drastically diverge, then those ODE are “stiff”
• Nonstiff ones can be solved by simpler numerical techniques, without risk of diverging.

• Whether a given ODE is stiff or non-stiff cannot be identified by simply looking at the ODE.
• Long practice and experience needed for this.
21
Solving ODE Numerically
• Stiff solver algorithms may provide incorrect results or compute very slowly for nonstiff
ODEs, and vice versa.
• There is no sharp boundary between stiff and nonstiff equations.

• There are several stiff and nonstiff solvers: ode45, ode23, ode113, ode15s, ode23s, ode23t,
ode23tb, ode15i

• If you think stiff one solving taking too long by nonstiff solver, press Ctrl+C on command
window to terminate

22
Strategy to choose solver
1. Assume ODE to be Nonstiff. First choice ode45
2. If you suspect some moderate stiffness, use ode23, Doing so would make the solution faster
but may result in some error. To minimize error (but taking a longer time), use ode113
3. If solution is taking too long or failing, you may suspect this is stiff ODE.
4. Now first try with ode15s. If facing problems, then alternatively try ode23s,ode23t, ode23tb
5. If still facing problems, then the stiff ODE might have no explicit solution. For implicit
solution, try ode15i
6. If still problem persists, you have run out of options, unfortunately! (Beyond scope of this
course)

23
Coupled Nonlinear ODEs- Inspiration
• Coupled ODEs with similar structure can be used to model phenomenon in Materials
Engineering and Beyond , at apparently unrelated fields.
• Consider the Problem with crystal growth
• Suppose there is a relatively large reaction vessel.
• Normally, an alpha phase grows in this vessel indefinitely.
• However, if an inoculant is added, then a beta phase begins to grow at the expense of the alpha
phase.
• Thus, the beta phase will grow as long as there is sufficient alpha phase to produce it.
• But if alpha phase amount is too low, then beta phase can no longer grow and dissolve back,
leading to a regrowth of the alpha phase.
• Thus there is an oscillation of the relative amounts of the alpha and beta phases , as long as
temperature is kept near crystallization temperature.
• We can think about this problem in analogy to the interaction between a population of
predators and prey in a forest.
24
Coupled nonlinear ODEs, hear the stories
In a Forest In a Crystal growth vessel
• There are Two kinds of Animals, Predator • There are Two kinds of Phases, Beta and
and Prey. Predator consumes Prey. Prey can Alpha . Beta consumes Alpha . Alpha can
grow (almost) indefinitely without Predator, grow (almost) indefinitely without Beta, but
but Predator without prey soon dies Beta without Alpha soon dissolves
• Let x be Prey and y be Predator amount vary • Let x be Beta and y be Alpha crystal amount
with time t. No. of Encounters between Prey vary with time t. No. of Collisions between
and Predator per unit time is proportional to Alpha and Beta per unit time is proportional
xy to xy
• Growth rate of Prey without Predator is 𝑎, • Growth rate of Alpha without Beta is 𝑎, and
and let rate of consumption of Prey per let rate of consumption of Alpha per collision
encounter is 𝑏. Then 𝑑𝑥/𝑑𝑡 = 𝑎𝑥 − 𝑏𝑥𝑦 is 𝑏. Then 𝑑𝑥/𝑑𝑡 = 𝑎𝑥 − 𝑏𝑥𝑦
• Death rate of predator in absence of Prey is 𝑐, • Dissolution rate of Beta in absence of Alpha
and let Predator growth rate for consumption is 𝑐, and let Beta growth rate for consumption
of Prey per encounter is 𝑑. Then 𝑑𝑦/𝑑𝑡 = of Alpha per collision is 𝑑. Then 𝑑𝑦/𝑑𝑡 =
− 𝑐𝑦 + 𝑑𝑥𝑦 − 𝑐𝑦 + 𝑑𝑥𝑦
25
What is problem with ‘Coupled’?
• So we have the following equations
𝑑𝑥 𝑑𝑦
= 𝑎𝑥 − 𝑏𝑥𝑦 ; = −𝑐𝑦 + 𝑑𝑥𝑦
𝑑𝑡 𝑑𝑡

• Rate of change of x depends on not just x but also y, and rate of change of y depends on not
just y but also x
• Since we cannot solve for x and y independently from each individual ODE, we call this system of
ODE ‘Coupled’

• Suppose we want to solve = 4𝑥 − 0.2𝑥𝑦; = −3𝑦 + 0.1𝑥𝑦 with condition 𝑥 0 =


10; 𝑦 0 = 100, with 0 to 10 time
• Try the code analytically: what do you find?
• Warning: Unable to find symbolic solution

26
Systems of ODE numerically

• Now use the numerical method (y(1) in place of x, y(2) in place of y)


• f = @(t,y)[4*y(1)-0.2*y(1)*y(2);0.1*y(1)*y(2)-3*y(2)]; % Define
the ODEs; 1st term for y’(1) 2nd term for y’(2)
• y0 = [10;100]; % Initial prey-predator popul. respectively
• % note the ; to separate two ODEs at first line, and their initial
conditions at second line
• tspan=[0 10]; % Start and end time
• [t,y]=ode45(f, tspan, y0); % Solve the ODEs
• plot(t,y(:,1),'b-',t,y(:,2),'r--'); % Plot the population dynamics
• xlabel('Time');ylabel('Population');legend('Prey','Predator');
• By default, ode45 chooses its own internal time step to ensure accuracy, so the time points in t
might not be uniformly spaced.
• If you change the constants a,b,c,d too much beyond some certain range, it becomes Nonstiff.27
See the results!
10 prey
30 prey
100
30
predator
predator

100 prey 100 prey


10 100
predator predator

28
Nonlinear higher-order ODE- inspiration
• 𝑑²𝑥/𝑑𝑡² + 𝑥 𝑑𝑥/𝑑𝑡 + 𝑡²/(𝑑𝑥/𝑑𝑡) = 𝐴
• In the context of a vibrating viscoelastic system, we can interpret the terms as follows:
• (𝑑²𝑥)/(𝑑𝑡²) represents the acceleration of the vibrator, rate of change of velocity

• 𝑥 (𝑑𝑥)/(𝑑𝑡): This term represents the influence of viscoelastic damping, where the damping
force is proportional to the product of displacement and velocity.

• 𝑡²/(𝑑𝑥/𝑑𝑡): This term represents a time-dependent contribution to the damping.

• A: This constant term represents Net external forces or excitations acting on the vibrator. It
could be due to applied loads, boundary conditions, or other factors influencing the system.

29
Nonlinear higher-order ODE
• For example, Suppose you need solving +𝑥 + = 2 and boundary condition 𝑥 0 =
3, 𝑥′(0) = 4.
• Solving it analytically is not possible (have a try!)
>> syms x(t)
eqn = diff(x,t,2)+x*diff(x)+(t^2)/diff(x)==2;
p=diff(x);
S = dsolve(eqn,[x(0)==3;p(0)==4])
Warning: Unable to find symbolic solution..

• If you try with any nonstiff solver like ode45, ode23 or ode113, it would take a pathetically
long time to solve on MATLAB (and even MATLAB can crash as well!)
• Try yourself if you do not believe!

• So, let us try the stiff algorithm now.

30
Nonlinear higher-order ODE
• We need to convert it to two coupled 1st order ODEs first
𝑑𝑦 𝑑𝑣 t
= 𝑣; = −xv − + 2
𝑑𝑡 𝑑𝑡 v
• Or we may use ode2VectorField to have that hint
• May replace the square brackets [] with parenthesis() and Y with y
• We try numerically , t ranging from 0 to 1. Treat x as y(1) and dx/dt (or v) as y(2)

• f = @(t,y)[y(2);-y(1)*y(2)-(t^2)/y(2)+2]; % Define the ODEs


• y0 = [3;4]; tspan=[0 1];%y(1) y(2) initial values; then Start and
end t
• [t,y]=ode15s(f, tspan, y0); % Solve the ODEs
• plot(t,y(:,1),'b-',t,y(:,2),'r--'); % Plot the equation
legend(‘Function’,’Slope’);% y(1) is function, y(2) is slope
• This equation is a stiff one, so we used ode15s.
31
Nonlinear higher-order ODE-Plot

32
Homework Problem
• Often heavy chains in factories are about to
touch ground peoples and vehicles, causing
mishap. Slender metallic bars can also sag
under heat(and modellable like chain), as the
case for many metallurgical factories. Equation
of profile of a non-expandable hanging heavy
chain or rope under its own load 𝑦(𝑥) is given
as
𝑑 𝑑𝑦 𝜆𝑔 𝑑𝑦
= ; 𝑑𝑠 = 𝑑𝑥 1 +
𝑑𝑠 𝑑𝑥 𝑇 𝑑𝑥
• Here 𝜆, 𝑔, 𝑇 means mass per unit length of
rope, gravitational acceleration and Tension at
bottom point of hanging rope respectively. The
rope is flat at bottom point, of course.
33
Homework Problem
1. Showing necessary steps, put the ODE into a form recognizable by MATLAB, and write that
into MATLAB script

2. Assuming bottom of the rope as origin, solve the ODE for analytic or explicit form of y(x)
and also s(x)

1. Hint: = 1+ can be part of system of linear ODEs as well

3. Numerically solve the ODE. Since you do not know numerical values of constants,
multiply all length scales (x,y,s) by to have non-dimensional form of the ODE to solve for
as a function of

34

You might also like