system of differential equations with ode45 in matlab - matlab

I have got this model for glucose and insulin, and system of differential equations:
Where:
G(t) - the plasma glucose concentration at time t
I(t) - the plasma insulin concentration at time t
X(t)- the interstitial insulin at time t
Gb - the basal plasma glucose concentration
Ib - the basal plasma insulin concentration
which describe the model. I must do an algorithm to estimate parameters with use ode45 in matlab.
Test data is as follows:
I am not sure how write function for ode45, my idea is as follows:
function [] = cwiczenie3_1a(dane)
a=size(dane);
u=[];
y=[];
for i=1:a(1,1)
g(i,1)=dane(i,2);
j(i,1)=dane(i,3);
end
[x t]=ode45(#funkcjajeden,[0 100],[0,0])
end
function [dg] = funkcjajeden(t,g)
gb=350;
d=0.1;
ib=120;
k1=1;
k2=2;
k3=1;
dg=zeros(size(g));
dg(1)=(k1*(gb-g(1)))-d*g(1);
dg(2)=(k2*(g(2)-ib))-k3*d;
end

Taking a look to the documentation for ode45 to solve the system of differential equations you should write the function in a file, odefcn.m in this case:
function dg = odefcn(g,k1,k2,k3,gb,ib,d)
dg = zeros(size(g));
dg(1) = k1*(gb-g(1)) - d*g(1);
dg(2) = k2*(g(2)-ib) - k3*d;
And then in another file you solve it by doing:
gb = 350;
d = 0.1;
ib = 120;
k1 = 1;
k2 = 2;
k3 = 1;
tspan = [0 100];
g0 = [0 0];
[t,g] = ode45(#(t,g) odefcn(g,k1,k2,k3,gb,ib,d), tspan, g0);
plot(t,g(:,1),t,g(:,2))
This way you obtain the values for both G(t) an I(t) for that initial values and parameters:
Image
Then, you can compare to the test data and find the value of the parameters.

Related

Spring/Damper Calculation & Plotting

Given two systems with damper/spring:
First system's simulink model with step time 2, final value 0.5:
Simulink of the second system with same input:
I have to find the code using dsolve and ode45 to generate the same graph with Simulink. Given values are:
m1 = 500
c1 = 1200
k1 = 25000
k2 = 15000
m2 = 50
I tried to find dsolve but it couldn't solve it. So I got to use ode45, and I am totally lost.
Differential equation of the first system:
syms x(t) y(t)
Dy = diff(y,t);
Dx = diff(x,t);
D2x = diff(x,2,t);
cond = [x(0)==0, y(0)==0, Dy(0)==0, Dx(0)==5];
eqn33 = D2x + (2*0.2121*0.1414*Dx) + (0.1414^2)*x==2*0.2121*0.1414*Dy+(0.1414^2)*y;
sol33 = dsolve(eqn33,cond)
pretty(sol33)
Answer updated to match Simulink model implementation
To use ode45, you first need to write a function that computes the derivative of you input vector (i.e. your differential equation), and store that function in a separate file with the function name as the filename. Please note that the ode solvers can only solve first-order differential equations, so you first need to do a bit of work to convert your second-order differential equation to a first-order one. For more details, see the documentation on ode45.
Based on what you have done in your Simulink model, D2y is known for all values of t (it's the step input), so we need to integrate it with respect to time to get Dy and y. So our state vector is X = [x; Dx; y; Dy] and our function looks like (stored in diff_eqn.m):
function dX = diff_eqn(t,X)
m1=500;
c=1200;
k1=25000;
dX(1) = X(2); % Dx
dX(2) = -(1/m1)*(c*(X(2)-X(4)/m1) + k1*(X(1)-X(3)/m1));; % D2x
dX(3) = X(4); % Dy
if t<2
dX(4) = 0; % D2y
else
dX(4) = 0.5;
end
as dX = [Dx; D2x; Dy; D2y].
In your script or your MATLAB command window, you can then call the ode solver (initial conditions all being equal to zero for Dx, x, Dy and y, as per your Simulink model):
[t,X] = ode45(#diff_eqn,[0 20],[0; 0; 0; 0]);
Adjust the ode solver options (e.g. max step size, etc...) to get results with more data points. To get the same plot as in your Simulink model, you can then process the results from the ode solver:
D2x = diff(X(:,2))./diff(t);
D2x = [0; D2x];
D2y = zeros(size(D2x));
D2y(t>=2) = 0.5;
plot(t,[D2y 500*D2x])
grid on
xlabel('Time [s]')
legend('D2y','m1*D2x','Location','NorthEast')
Which gives the following plot, matching the results from your Simulink model:

MATLAB - passing a sinusoidal forcing function to ode45

I'm new to Matlab and am really struggling even to get to grips with the basics.
I've got a function, myspring, that solves position and velocity of a mass/spring system with damping and a driving force. I can specify values for the spring stiffness (k), damping coefficient (c), and mass (m), in the command window prior to running ode45. What I am unable to do is to define a forcing function (even something simple like g = sin(t)) and use that as the forcing function, rather than having it written into the myspring function.
Can anyone help? Here's my function:
function pdot = myspring(t,p,c,k,m)
w = sqrt(k/m);
g = sin(t); % This is the forcing function
pdot = zeros(size(p));
pdot(1) = p(2);
pdot(2) = g - c*p(2) - (w^2)*p(1);
end
and how I'm using it in the command window:
>> k = 2; c = 2; m = 4;
>> tspan = linspace(0,10,100);
>> x0 = [1 0];
>> [t,x] = ode45(#(t,p)myspring(t,p,c,k,m),tspan,x0);
That works, but what I want should look something like this (I imagine):
function pdot = myspring(t,p,c,k,m,g)
w = sqrt(k/m);
pdot = zeros(size(p));
pdot(1) = p(2);
pdot(2) = g - c*p(2) - (w^2)*p(1);
end
Then
g = sin(t);
[t,x] = ode45(#(t,p)myspring(t,p,c,k,m,g),tspan,x0);
But what I get is this
In an assignment A(:) = B, the number of elements in A and B must be the same.
Error in myspring (line 7)
pdot(2) = g - c*p(2) - (w^2)*p(1);
Error in #(t,p)myspring(t,p,c,k,m,g)
Error in odearguments (line 87)
f0 = feval(ode,t0,y0,args{:}); % ODE15I sets args{1} to yp0.
Error in ode45 (line 115)
odearguments(FcnHandlesUsed, solver_name, ode, tspan, y0, options, varargin);
Horchler, thank you for the reply. I can do as you suggested and it works. I am now faced with another problem that I hope you could advise me on.
I have a script that calculates the force on a structure due to wave interaction using Morison's equation. I gave it an arbitrary time span to begin with. I would like to use the force F that script calculates as the input driving force to myspring. Here is my Morison script:
H = 3.69; % Wave height (m)
A = H/2; % Wave amplitude (m)
Tw = 9.87; % Wave period (s)
omega = (2*pi)/Tw; % Angular frequency (rad/s)
lambda = 128.02; % Wavelength (m)
k = (2*pi)/lambda; % Wavenumber (1/m)
dw = 25; % Water depth (m)
Cm = 2; % Mass coefficient (-)
Cd = 0.7; % Drag coefficient (-)
rho = 1025; % Density of water (kg/m^3)
D = 3; % Diameter of structure (m)
x = 0; % Fix the position at x = 0 for simplicity
t = linspace(0,6*pi,n); % Define the vector t with n time steps
eta = A*cos(k*x - omega*t); % Create the surface elevation vector with size equal to t
F_M = zeros(1,n); % Initiate an inertia force vector with same dimension as t
F_D = zeros(1,n); % Initiate a drag force vector with same dimension as t
F = zeros(1,n); % Initiate a total force vector with same dimension as t
fun_inertia = #(z)cosh(k*(z+dw)); % Define the inertia function to be integrated
fun_drag = #(z)(cosh(k*(z+dw)).*abs(cosh(k*(z+dw)))); % Define the drag function to be integrated
for i = 1:n
F_D(i) = abs(((H*pi)/Tw) * (1/sinh(k*dw)) * cos(k*x - omega*t(i))) * ((H*pi)/Tw) * (1/sinh(k*dw)) * cos(k*x - omega*t(i)) * integral(fun_drag,-dw,eta(i));
F_M(i) = (Cm*rho*pi*(D^2)/4) * ((2*H*pi^2)/(Tw^2)) * (1/(sin(k*dw))) * sin(k*x - omega*t(i)) * integral(fun_inertia,-dw,eta(i));
F(i) = F_D(i) + F_M(i);
end
Any further advice would be much appreciated.
You can't pre-calculate your forcing function. It depends on time, which ode45 determines. You need to define g as a function and pass a handle to it into your integration function:
...
g = #(t)sin(t);
[t,x] = ode45(#(t,p)myspring(t,p,c,k,m,g),tspan,x0);
And then call it I n your integration function, passing in the current time:
...
pdot(2) = g(t) - c*p(2) - (w^2)*p(1);
...

Modeling SIR model in matlab and simulink

I am trying to model a SIR epidemic model in matlab and simulink. I think I've already done it in matlab but for some reason my simulink model won't work. It just shows straight lines in a scope. This is my function to calculate differential equations.
function dx = sir(t, x)
dx = [0; 0; 0];
beta = .5;
delta = .3;
dx(1) = -beta * x(1) * x(2);
dx(2) = beta * x(1) * x(2) - delta * x(2);
dx(3) = delta * x(2);
end
This is my workspace code to show plot
and this is mu simulink with yields this strange plot and this is after autoscaling with initial conditions set to S = 7900000 and R = 0 and I = 10
The List of Signals property of the summation block that is being fed by the Product3 and Product2 blocks should be |+- instead of |--.

ODE - Solving Parameter Dependent on Variable [Matlab]

Lets say I have a function file of the ODE that goes like this
function xprime = RabbitTemp(t,X)
% Model of Rabbit Population
% where,
% Xo = Initial Population of Rabbits
% X(1) = Population density of Rabbit
% X(2) = Temperature T (that varies with time)
% a = test parameter
%%% ODE
a = 10;
dx(1) = (X(1))*(1 - a*X(1) - 3*(X(2))));
dx(2) = sin(t);
%%%%%%%
xprime = [dx(1) dx(2)]';
end
But what if I would like parameter a to vary as temperature X(2) varies, as the ODE solver calculates.
I understand I would first have to create some data between a and X(2) and interpolate it. But after that I'm not very sure what's next. Could any one point me in the right direction?
Or is there any other way?
It really depends on the function of a, a=f(T). If you can take the derivative of f(T) I suggest you include a as another state, for instance X(3) and then you can access it from the X argument in xprime easily, plus it will help Matlab determine the proper step size during integration:
function xprime = RabbitTemp(t,X)
% Model of Rabbit Population
% where,
% Xo = Initial Population of Rabbits
% X(1) = Population density of Rabbit
% X(2) = Temperature T (that varies with time)
% X(3) = test parameter
%%% ODE
a = 10;
Yo = 0.4; %Just some Constant
dx(1) = (X(1))*(1 - X(1)^(a) - Yo*(X(2))));
dx(2) = sin(t);
dx(3) = ....
%%%%%%%
xprime = [dx(1) dx(2) dx(3)]';
end
Second method is to create a function(-handle) for a=f(T) and call it from within xprime:
function xprime = RabbitTemp(t,X)
% Model of Rabbit Population
% where,
% Xo = Initial Population of Rabbits
% X(1) = Population density of Rabbit
% X(2) = Temperature T (that varies with time)
% a = test parameter
%%% ODE
a = f_a(t,X);
Yo = 0.4; %Just some Constant
dx(1) = (X(1))*(1 - X(1)^(a) - Yo*(X(2))));
dx(2) = sin(t);
%%%%%%%
xprime = [dx(1) dx(2)]';
end
function a = f_a(t,X)
return 10; % You might want to change this.
end
If possible go with the first variant which is creating another state for a.

Using ode45 in Matlab

I'm trying to simulate the time behavior for a physical process governed by a system of ODEs. When I switch the width of the input pulse from 20 to 19, there is no depletion of the y(1) state, which doesn't make sense physically. What am I doing wrong? Am I using ode45 incorrectly?
function test
width = 20;
center = 100;
tspan = 0:0.1:center+50*(width/2);
[t,y] = ode45(#ODEsystem,tspan,[1 0 0 0]);
plot(t,y(:,1),'k*',t,y(:,2),'k:',t,y(:,3),'k--',t,y(:,4),'k');
hold on;
axis([center-3*(width/2) center+50*(width/2) -0.1 1.1])
xlabel('Time')
ylabel('Relative values')
legend({'y1','y2','y3','y4'});
function dy = ODEsystem(t,y)
k1 = 0.1;
k2 = 0.000333;
k3 = 0.1;
dy = zeros(size(y));
% rectangular pulse
I = rectpuls(t-center,width);
% ODE system
dy(1) = -k1*I*y(1);
dy(2) = k1*I*y(1) - k2*y(2);
dy(3) = k2*y(2) - k3*I*y(3);
dy(4) = k3*I*y(3);
end
end
You are changing the parameters of your your ODEs discontinuously in time. This results in a very stiff system and less accurate, or even completely wrong, results. In this case, because the your ODE is so simple when I = 0, an adaptive solver like ode45 will take very large steps. Thus, there's a high probability that it will step right over the region where you inject the impulse and never see it. See my answer here if you're confused as to why the code in your question misses the pulse even though you've specified tspan to have (output) steps of just 0.1.
In general it is a bad idea to have any discontinuities (if statements, abs, min/max, functions like rectpuls, etc.) in your integration function. Instead, you need to break up the integration and calculate your results piecewise in time. Here's a modified version of your code that implements this:
function test_fixed
width = 19;
center = 100;
t = 0:0.1:center+50*(width/2);
I = rectpuls(t-center,width); % Removed from ODE function, kept if wanted for plotting
% Before pulse
tspan = t(t<=center-width/2);
y0 = [1 0 0 0];
[~,out] = ode45(#(t,y)ODEsystem(t,y,0),tspan,y0); % t pre-calculated, no need to return
y = out;
% Pulse
tspan = t(t>=center-width/2&t<=center+width/2);
y0 = out(end,:); % Initial conditions same as last stage from previous integration
[~,out] = ode45(#(t,y)ODEsystem(t,y,1),tspan,y0);
y = [y;out(2:end,:)]; % Append new data removing identical initial condition
% After pulse
tspan = t(t>=center+width/2);
y0 = out(end,:);
[~,out] = ode45(#(t,y)ODEsystem(t,y,0),tspan,y0);
y = [y;out(2:end,:)];
plot(t,y(:,1),'k*',t,y(:,2),'k:',t,y(:,3),'k--',t,y(:,4),'k');
hold on;
axis([center-3*(width/2) center+50*(width/2) -0.1 1.1])
xlabel('Time')
ylabel('Relative values')
legend({'y1','y2','y3','y4'});
function dy = ODEsystem(t,y,I)
k1 = 0.1;
k2 = 0.000333;
k3 = 0.1;
dy = zeros(size(y));
% ODE system
dy(1) = -k1*I*y(1);
dy(2) = k1*I*y(1) - k2*y(2);
dy(3) = k2*y(2) - k3*I*y(3);
dy(4) = k3*I*y(3);
end
end
See also my answer to a similar question.