Professional Documents
Culture Documents
Using Ode45 (Runge-Kutta 4th and 5th Order)
Using Ode45 (Runge-Kutta 4th and 5th Order)
Examples of ode45
One dependent variable with anonymous function
First-order reaction dy/dt = -0.3*y
f1=@(t,y) -0.3*y;
[t,y]=ode45(f1,[0 10],[100]);
set(gca, 'fontsize',14,'fontweight','bold');
%sets the fontsize of the axis numbers
plot(t,y)
xlabel('time (min)','fontsize',16)
ylabel('y','fontsize',16)
function dy = firstorder(t,y)
%this is the function m file
%first-order differential equation
k=0.4;
dy(1)= -k*y(1);
end
Find the solution, h(t), for 0 < t < 30 if the following parameters are given: b = 2 h0 = 1
function dhdt=tankfill(t,h)
%RHS function for tank-fill problem
A= 10 + 4*sin(t); %alpha(t)
H = 2*sqrt(h); %beta*sqrt(h)
dhdt = A - H;
end
tspan = [0 30];
>> h0 = 1;
>> [t,h]=ode45(@tankfill,tspan,h0);
>> plot(t,h)
>> figure
>> plot(t,h)
>> tspan=linspace(0,30,300);
>> [t,h]=ode45(@tankfill,tspan,h0);
>> figure
>> plot(t,h)
= 2 y 4e
dt
dz
dt
yz
function dy = pair(t,y)
%example of pair of differential equations
dy=zeros(2,1); %make sure dy is a column vector
dy(1)= -2.*y(1)+4*exp(-t);
dy(2)= -(y(1).*y(2).^2)/3;
end
Results:
y(t, length(y0))
2.00
1.98
1.93
1.87
1.78
4.00
3.16
2.62
2.25
1.98
function dy = pair(t,y,a,b,c)
dy(1)= -a.*y(1)+b*exp(-t); dy(2)= -(y(1).*y(2).^2)/c;
end
tspan=0:0.1:0.4;
a=2; b= 4; c=3;
[t,y]=ode45(@pair,tspan,[2 4],[ ], a,b,c);
dz
dt
yz
c