Está en la página 1de 5

Metodo de rungger kuta de orden 4

function tx=rk4(f,tt,x0)
n=length(tt)
tx(1)=x0
for k=2:n
h=tt(k)-tt(k-1);
f1=h*f(tt(k-1),tx(k-1));
f2=h*f(tt(k-1)+h/2,tx(k-1)+f1/2);
f3=h*f(tt(k-1)+h/2,tx(k-1)+f2/2);
f4=h*f(tt(k-1)+h,tx(k-1)+f3);
tx(k)=tx(k-1)+(f1+2*f2+2*f3+f4)/6;
end

function x=ejm1(t)
f=@(t,x) x.*sin(t);
tt=[0 0.1 0.2 0.3 0.4 0.5];
tx=rk4(f,tt,2);
x=interp1(tt,tx,t,'spline');

>> t=[0 0.1 0.2 0.3 0.4 0.5];


>> x=ejm1(t)

n =

tx =

x =

2.0000 2.0100 2.0403 2.0914 2.1643 2.2605


Ejemplo 2
function tx=rk4(f,tt,x0)
n=length(tt)
tx(1)=x0
for k=2:n
h=tt(k)-tt(k-1);
f1=h*f(tt(k-1),tx(k-1));
f2=h*f(tt(k-1)+h/2,tx(k-1)+f1/2);
f3=h*f(tt(k-1)+h/2,tx(k-1)+f2/2);
f4=h*f(tt(k-1)+h,tx(k-1)+f3);
tx(k)=tx(k-1)+(f1+2*f2+2*f3+f4)/6;
end

function dx=ecua(t,x)
dx=x.*exp(-t.*sqrt(x));

function x=solu(t)
tt=0:0.1:2*pi;
f=@(t,x) ecua(t,x);
tx=rk4(f,tt,3);
x=interp1(tt,tx,t,'spline');

>> plot(t,x),grid on
>> t=0:0.01:2*pi;
>> x=sin(t+solu(t));

n =
63

tx =

>> plot(t,x),grid on

Solución de la ecuación diferencial


>> t=0:0.01:2*pi;

>> x=solu(t);

n=

63

tx =

>> plot(t,x),grid on
Ejemplo 3

function tx=rk4(f,tt,x0)
n=length(tt)
tx(1)=x0
for k=2:n
h=tt(k)-tt(k-1);
f1=h*f(tt(k-1),tx(k-1));
f2=h*f(tt(k-1)+h/2,tx(k-1)+f1/2);
f3=h*f(tt(k-1)+h/2,tx(k-1)+f2/2);
f4=h*f(tt(k-1)+h,tx(k-1)+f3);
tx(k)=tx(k-1)+(f1+2*f2+2*f3+f4)/6;
end

function dy=ecua1(x,y)
dy=x+y;

function y=solu1(x)
tx=0:0.1:pi;
f=@(x,y)ecua1(x,y);
ty=rk4(f,tx,3);
y=interp1(tx,ty,x,'spline');

>> g=@(x)cos(solu1(x));

>> quad(g,0,pi)

ans =

-0.1204

También podría gustarte