Problem with runge-kutta adaptive algorithm
5 views (last 30 days)
Show older comments
Hey,
I have the following problem. I'm trying to write a program in Matlab, that would implement Runge-Kutta 2 algorithm, but with changing step size, so the adaptive one. In the main script I need to write a code based on this pseudocode:
while(t<tk)
h=h_start; // h-step size
while(crit>eps)
y_next=RK2(t, y, h); //here RK2 method is called
y_next_2=RK2(t, y, h/2);
y_next_2=RK2(t, y_next_2, h/2);
crit=norm(y_next-y_next_2);
if(crit>eps)
h=h/2;
end
y(t+1)=y_next_2;
end
end
So, basicaly what's need to be done, is to draw one point of a diagram in each loop, changing the step size h until criterium (crit) is less than epsilon (eps).
Below, there is the code I've already done in Matlab. The problem is, in this code I'm not getting one diagram but few of them, because the plot function is in the loop of the RK2 method. I couldn't find any other way to send the values of the function to the main script.
Here's the script:
Main:
h_start=5;
%h_start=0.1;
h=h_start;
crit=1;
eps=0.00001;
q=1;
while(crit>eps)
y_next=RK2(h);
y_next_2=RK2(h/2);
crit=norm(y_next_2-y_next);
if(crit>eps)
h=h/2;
end
q=q+1;
end
%plot(t, y2, 'r');
q
RK2:
function [y1, t] = RK2(h)
y1(1)=0; %initial conditions
y2(1)=0;
p(1)=0;
c1=0.26;
c2=0.1;
c3=1;
a=0.13;
b=0.013;
F_xy= @(t, y1, y2, p) c1*y1*(y1-a)*(1-y1)-c2*y2+p;
G_xy= @(t, y1, y2) b*(y1-c3*y2);
t(1)=0;
n=80;
%n=2000;
for j = 1:n
if(t(j)>50 && t(j)<60)
p(j)=0.05;
else
p(j)=0;
end
k1 = h * F_xy(t(j), y1(j), y2(j), p(j));
l1= h * G_xy(t(j), y1(j), y2(j));
k2 = h * F_xy( t(j) + h/2, y1(j) + k1/2, y2(j) + k1/2, p(j));
l2 = h * G_xy( t(j) + h/2, y1(j) + l1/2, y2(j) + l1/2);
y1(j+1) = y1(j) + (k1 + k2)/2;
y2(j+1) = y2(j) + (l1 + l2)/2;
t(j+1)=t(j)+h;
hold on
plot(t, y1, 'r');
end
end
3 Comments
Answers (0)
See Also
Categories
Find more on Interpolation in Help Center and File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!