function [t,x,y,N] = Runge4_2eqs(f1,f2,to,tfinal,xo,yo,h)
N = ceil((tfinal-to)/h);
x = zeros(1,N);
y = zeros(1,N) ;
x(1) = xo;
y(1) = yo;
t = to;
for i = 1:N
t(i+1) = t(i)+h;
Sx1 = f1(t(i),x(i),y(i));
Sy1 = f2(t(i),x(i),y(i));
Sx2 = f1(t(i)+h/2, x(i)+Sx1*h/2, y(i)+Sy1*h/2);
Sy2 = f2(t(i)+h/2, x(i)+Sx1*h/2, y(i)+Sy1*h/2);
Sx3 = f1(t(i)+h/2, x(i)+Sx2*h/2, y(i)+Sy2*h/2);
Sy3 = f2(t(i)+h/2, x(i)+Sx2*h/2, y(i)+Sy2*h/2);
Sx4 = f1(t(i)+h, x(i)+Sx3*h, y(i)+Sy3*h);
Sy4 = f2(t(i)+h, x(i)+Sx3*h, y(i)+Sy3*h);
x(i+1) = x(i) + (h/6)*(Sx1+2*Sx2+2*Sx3+Sx4);
y(i+1) = y(i) + (h/6)*(Sy1+2*Sy2+2*Sy3+Sy4);
end
function f1 = DvDX(t,x,y)
f1 = y;
end
function f2 = DvDT(t,x,y)
c = 0.16; m = 0.5; g = 9.81; L = 1.2;
f2 = -(c/m)*y - (g/L)*sin(x);
end
clear variables
colse all
xo = pi/2;
yo = 0;
h = .020;
to = 0;
tfinal = 20;
[t,x,y,N] = Runge4_2eqs(@DvDX,@DvDT,to,tfinal,xo,yo,h);
figure(1); clf(1)
plot(t,x, 'Linewidth', 1.5, 'color', 'r')
hold on
plot(t,y,'Linewidth', 1.5, 'color', 'b')
legend('Dfx','Dfy')
title('Solution to two systems of ODEs')
xlabel('x')
ylabel('y')
xlim([to tfinal])
grid
Best Answer