% Metodo de Kutta de ordem 3 integrado num intervalo (ti,tf) 
% com condicao inicial (t0,x0) e passo h

function x = RK3_twosidded(ti,t0,tf,h,x0,F)

 % integracao no futuro

   tp = (t0:h:tf)';

    xp = zeros(length(tp),length(x0));
    xp(1,:) = x0;
    
    for i = 2:length(tp)
        
        k1 = F(tp(i-1),xp(i-1,:));
        k2 = F(tp(i-1) + h/2, xp(i-1,:)+ (h/2).*k1);
        k3 = F(tp(i), xp(i-1,:) + h.*(2.*k2 - k1));
        xp(i,:) = xp(i-1,:) + (h/6).*(k1+ 4.*k2 + k3);
        
    end

    % integracao no passado

    tm = (ti:h:t0)';

    xm = zeros(length(tm),length(x0));
    xm(length(tm),:) = x0;
    
    for i = 1:length(tm)-1
 
        j = length(tm)-i;
        k1 = F(tm(j+1),xm(j+1,:));
        k2 = F(tm(j+1) - h/2, xm(j+1,:) - (h/2).*k1);
        k3 = F(tm(j), xm(j+1,:) - h.*(2.*k2 - k1));
        xm(j,:) = xm(j+1,:) - (h/6).*(k1+ 4.*k2 + k3);
        
    end

% concatenacao

    x=[xm(1:length(tm)-1);xp];
    

end