Solving a 4 ODE system in MATLAB using ode45 - matlab

I am not very used to MATLAB and I'm trying to solve the following problem using MATLAB ode45, however, it's not working.
I was working on a problem in reaction engineering, using a Semi-Batch Reactor.
The reaction is given by
A + B ---> C + D
A is placed in the reactor and B is being continuously added into the reactor with a flowrate of v0 = 0.05 L/s. Initial volume is V0 = 5 L. The reaction is elementary. The reaction constant is k = 2.2 L/mol.s.
Initial Concentrations: for A: 0.05 M, for B: 0.025 M.
Performing a mole balance of each species in the reactor, I got the following 4 ODEs, and the expression of V (volume of the reactor is constantly increasing)
Solving this system and plotting the solution against time, I should get this
Note that plots of C(C) and C(D) are the same.
And let's set tau = v0/V.
Now for the MATLAB code part.
I have searched extensively online, and from what I've learned, I came up with the following code.
First, I wrote the code for the ODE system
function f = ODEsystem(t, y, tau, ra, y0)
f = zeros(4, 1);
f(1) = ra - tau*y(1);
f(2) = ra + tau*(y0(2) - y(2));
f(3) = -ra - tau*y(3);
f(4) = -ra - tau*y(4);
end
Then, in the command window,
t = [0:0.01:5];
v0 = 0.05;
V0 = 5;
k = 2.2;
V = V0 + v0*t;
tau = v0./V;
syms y(t);
ra = -k*y(1)*y(2);
y0 = [0.05 0.025 0 0];
[t, y] = ode45(#ODEsystem(t, y, tau, ra, y0), t, y0);
plot(t, y);
However, I get this...
Please if anyone could help me fix my code. This is really annoying :)

ra should not be passed as parameter but be computed inside the ODE system. V is likewise not a constant. Symbolic expressions should be used for formula transformations, not for numerical methods. One would also have to explicitly evaluate the symbolic expression at the wanted numerical values.
function f = ODEsystem(t, y, k, v0, V0, cB0)
f = zeros(4, 1);
ra = -k*y(1)*y(2);
tau = v0/(V0+t*v0);
f(1) = ra - tau*y(1);
f(2) = ra + tau*(cB0 - y(2));
f(3) = -ra - tau*y(3);
f(4) = -ra - tau*y(4);
end
Then use the time span of the graphic, start with all concentrations zero except for A, use the concentration B only for the inflow.
t = [0:1:500];
v0 = 0.05;
V0 = 5;
k = 2.2;
cB0 = 0.025;
y0 = [0.05 0 0 0];
[t, y] = ode45(#(t,y) ODEsystem(t, y, k, v0, V0, cB0), t, y0);
plot(t, y);
and get a good reproduction of the reference image

Related

How to solve a system of three first-order ODEs in Matlab

I am using Matlab to try and solve a system of three first-order ODEs, but the error message I get is 'syms' requires Symbolic Math Toolbox.
Error in spiders (line 1)
syms f(t) s(t) v(t) r W c h q a k b H K e
On a previous occasion, I received an error saying that this system of ODEs cannot be solved explicitly (i.e. in closed form). I think that numerical integration is the only way. The r,W,c,h, etc are parameters. Could someone please tell me how I can simulate/solve and plot the ODEs below?
syms f(t) s(t) v(t) r W c h q a k b H K e
r = 1;
W = 0.5;
c = 0.4;
h = 0.9;
q = 9;
a = 5;
k = 0.8;
b = 6;
H = 3;
K = 1.3;
e = 2;
ode1 = diff(f) == r*f*(1 - f/W) - c*s*f - h*(1 - q)*f;
ode2 = diff(s) == s*(-a + k*b*v/(H + v) + k*c*f) - h*K*q*s;
ode3 = diff(v) == v*(e - b*s/(H + v)) - h*q*v;
odes=[ode1;ode2;ode3]
S = dsolve(odes)
plot(S);
Looks like you where previously using a different MATLAB license, which included the Symbolic Math Toolbox. I assume you no longer have it available and you are now looking for numeric alternatives.
You have to define functions for the equations you are trying to solve. Then you can call one of the ode solvers. An example from the documentation:
y0 = [1; 0; 0];
tspan = [0 4*logspace(-6,6)];
M = [1 0 0; 0 1 0; 0 0 0];
options = odeset('Mass',M,'RelTol',1e-4,'AbsTol',[1e-6 1e-10 1e-6]);
[t,y] = ode15s(#robertsdae,tspan,y0,options);
Where robertsdae is the equation to solve. The full example including further explanations is available here.

DAE simulation interrupts

I have a problem using the MATLAB DAE-solvers.
I'm trying to simulate the behaviour of a mechanical system using lagrangien mechanics. To do so, I followed the following tutorial to use MATLAB'sDAE-solvers.
But when I ran my code, I got the following error message:
Warning: Failure at t=5.076437e-01. Unable to meet integration tolerances without reducing the step size below the smallest value allowed
(1.803513e-15) at time t.
In ode15i (line 406)
Trying to find my mistake, I literally copied the code from the tutorial and ran it. The code is as follows:
syms l g m real
syms x(t) y(t) T(t)
eqns = [(m*diff(x(t),2) - T(t)/l*x(t)),
(m*diff(y(t),2) - T(t)/l*y(t) + m*g),
(x(t)^2 + y(t)^2 - l^2) ];
vars = [x(t); y(t); T(t)];
[eqns, vars] = reduceDifferentialOrder(eqns, vars);
if(~isLowIndexDAE(eqns, vars))
[DAEs, DAEvars] = reduceDAEIndex(eqns, vars);
[DAEs, DAEvars] = reduceRedundancies(DAEs, DAEvars);
end
%change to function, set parameters
f = daeFunction(DAEs, DAEvars, m, l, g);
m = 1.0;
r = 1.0;
g = 9.81;
F = #(t, Y, YP) f(t, Y, YP, m, r, g);
%get initial conditions
y0est = [0.5*r; -0.8*r; 0; 0; 0; 0; 0];
yp0est = zeros(7,1);
opt = odeset('RelTol', 10.0^(-7), 'AbsTol' , 10.0^(-7));
[y0, yp0] = decic(F, 0, y0est, [], yp0est, [], opt);
%simulate
[t,y] = ode15i(F, [0, 5], y0, yp0, opt);

Solving System of Second Order Ordinary Differential Equation in Matlab

Introduction
I am using Matlab to simulate some dynamic systems through numerically solving systems of Second Order Ordinary Differential Equations using ODE45. I found a great tutorial from Mathworks (link for tutorial at end) on how to do this.
In the tutorial the system of equations is explicit in x and y as shown below:
x''=-D(y) * x' * sqrt(x'^2 + y'^2)
y''=-D(y) * y' * sqrt(x'^2 + y'^2) + g(y)
Both equations above have form y'' = f(x, x', y, y')
Question
However, I am coming across systems of equations where the variables can not be solved for explicitly as shown in the example. For example one of the systems has the following set of 3 second order ordinary differential equations:
y double prime equation
y'' - .5*L*(x''*sin(x) + x'^2*cos(x) + (k/m)*y - g = 0
x double prime equation
.33*L^2*x'' - .5*L*y''sin(x) - .33*L^2*C*cos(x) + .5*g*L*sin(x) = 0
A single prime is first derivative
A double prime is second derivative
L, g, m, k, and C are given parameters.
How can Matlab be used to numerically solve a set of second order ordinary differential equations where second order can not be explicitly solved for?
Thanks!
Your second system has the form
a11*x'' + a12*y'' = f1(x,y,x',y')
a21*x'' + a22*y'' = f2(x,y,x',y')
which you can solve as a linear system
[x'', y''] = A\f
or in this case explicitly using Cramer's rule
x'' = ( a22*f1 - a12*f2 ) / (a11*a22 - a12*a21)
y'' accordingly.
I would strongly recommend leaving the intermediate variables in the code to reduce chances for typing errors and avoid multiple computation of the same expressions.
Code could look like this (untested)
function dz = odefunc(t,z)
x=z(1); dx=z(2); y=z(3); dy=z(4);
A = [ [-.5*L*sin(x), 1] ; [.33*L^2, -0.5*L*sin(x)] ]
b = [ [dx^2*cos(x) + (k/m)*y-g]; [-.33*L^2*C*cos(x) + .5*g*L*sin(x)] ]
d2 = A\b
dz = [ dx, d2(1), dy, d2(2) ]
end
Yes your method is correct!
I post the following code below:
%Rotating Pendulum Sym Main
clc
clear all;
%Define parameters
global M K L g C;
M = 1;
K = 25.6;
L = 1;
C = 1;
g = 9.8;
% define initial values for theta, thetad, del, deld
e_0 = 1;
ed_0 = 0;
theta_0 = 0;
thetad_0 = .5;
initialValues = [e_0, ed_0, theta_0, thetad_0];
% Set a timespan
t_initial = 0;
t_final = 36;
dt = .01;
N = (t_final - t_initial)/dt;
timeSpan = linspace(t_final, t_initial, N);
% Run ode45 to get z (theta, thetad, del, deld)
[t, z] = ode45(#RotSpngHndl, timeSpan, initialValues);
%initialize variables
e = zeros(N,1);
ed = zeros(N,1);
theta = zeros(N,1);
thetad = zeros(N,1);
T = zeros(N,1);
V = zeros(N,1);
x = zeros(N,1);
y = zeros(N,1);
for i = 1:N
e(i) = z(i, 1);
ed(i) = z(i, 2);
theta(i) = z(i, 3);
thetad(i) = z(i, 4);
T(i) = .5*M*(ed(i)^2 + (1/3)*L^2*C*sin(theta(i)) + (1/3)*L^2*thetad(i)^2 - L*ed(i)*thetad(i)*sin(theta(i)));
V(i) = -M*g*(e(i) + .5*L*cos(theta(i)));
E(i) = T(i) + V(i);
end
figure(1)
plot(t, T,'r');
hold on;
plot(t, V,'b');
plot(t,E,'y');
title('Energy');
xlabel('time(sec)');
legend('Kinetic Energy', 'Potential Energy', 'Total Energy');
Here is function handle file for ode45:
function dz = RotSpngHndl(~, z)
% Define Global Parameters
global M K L g C
A = [1, -.5*L*sin(z(3));
-.5*L*sin(z(3)), (1/3)*L^2];
b = [.5*L*z(4)^2*cos(z(3)) - (K/M)*z(1) + g;
(1/3)*L^2*C*cos(z(3)) + .5*g*L*sin(z(3))];
X = A\b;
% return column vector [ed; edd; ed; edd]
dz = [z(2);
X(1);
z(4);
X(2)];

The Fastest Method of Solving System of Non-linear Equations in MATLAB

Assume we have three equations:
eq1 = x1 + (x1 - x2) * t - X == 0;
eq2 = z1 + (z1 - z2) * t - Z == 0;
eq3 = ((X-x1)/a)^2 + ((Z-z1)/b)^2 - 1 == 0;
while six of known variables are:
a = 42 ;
b = 12 ;
x1 = 316190;
z1 = 234070;
x2 = 316190;
z2 = 234070;
So we are looking for three unknown variables that are:
X , Z and t
I wrote two method to solve it. But, since I need to run these code for 5.7 million data, it become really slow.
Method one (using "solve"):
tic
S = solve( eq1 , eq2 , eq3 , X , Z , t ,...
'ReturnConditions', true, 'Real', true);
toc
X = double(S.X(1))
Z = double(S.Z(1))
t = double(S.t(1))
results of method one:
X = 316190;
Z = 234060;
t = -2.9280;
Elapsed time is 0.770429 seconds.
Method two (using "fsolve"):
coeffs = [a,b,x1,x2,z1,z2]; % Known parameters
x0 = [ x2 ; z2 ; 1 ].'; % Initial values for iterations
f_d = #(x0) myfunc(x0,coeffs); % f_d considers x0 as variables
options = optimoptions('fsolve','Display','none');
tic
M = fsolve(f_d,x0,options);
toc
results of method two:
X = 316190; % X = M(1)
Z = 234060; % Z = M(2)
t = -2.9280; % t = M(3)
Elapsed time is 0.014 seconds.
Although, the second method is faster, but it still needs to be improved. Please let me know if you have a better solution for that. Thanks
* extra information:
if you are interested to know what those 3 equations are, the first two are equations of a line in 2D and the third equation is an ellipse equation. I need to find the intersection of the line with the ellipse. Obviously, we have two points as result. But, let's forget about the second answer for simplicity.
My suggestion it's to use the second approce,which it's the recommended by matlab for nonlinear equation system.
Declare a M-function
function Y=mysistem(X)
%X(1) = X
%X(2) = t
%X(3) = Z
a = 42 ;
b = 12 ;
x1 = 316190;
z1 = 234070;
x2 = 316190;
z2 = 234070;
Y(1,1) = x1 + (x1 - x2) * X(2) - X(1);
Y(2,1) = z1 + (z1 - z2) * X(2) - X(3);
Y(3,1) = ((X-x1)/a)^2 + ((Z-z1)/b)^2 - 1;
end
Then for solving use
x0 = [ x2 , z2 , 1 ];
M = fsolve(#mysistem,x0,options);
If you may want to reduce the default precision by changing StepTolerance (default 1e-6).
Also for more increare you may want to use the jacobian matrix for greater efficencies.
For more reference take a look in official documentation:
fsolve Nonlinear Equations with Analytic Jacobian
Basically giving the solver the Jacobian matrix of the system(and special options) you can increase method efficency.

Solving Multiple Equations For Repeated Times With Different Initial Conditions Matlab

I have the following set of values in an array.
a = [a(1) a(2) ... a(1907)]
Gamma(1)= (u*f(1))+(r*a(1))
u and r are constant and f(n) changes during each step and its initial value is f(1) = zero.
f(n) next values will be generated from solving these equations.
h(1) = x(1) + Gamma(1) for which x(1)=0 and in next steps is constant. (c)
Z(1)= constant(T) * h(1)
f(2) = constant(G) * Z(1)
These steps will repeated 1907 times. Any idea what should I do at all?
You can input your initial conditions into a very simple for loop.
% a, u, r, T, G are assumed available.
f = zeros(1908, 1);
Z = zeros(1907 ,1);
Gamma = zeros(1907, 1);
x = [0; c*ones(1906, 1)];
for ii = 1:1907
Gamma(ii) = u*f(ii) + r*a(ii);
h(ii) = x(ii) + Gamma(ii);
Z(ii) = T*h(ii);
f(ii+1) = G*Z(ii);
end