% Runge-Kutta 2th Order vs ode23 Example
% to solve dy/dt = f(t,y), y(a)=y0, on [a,b]
clear

a=0;
b=1;
N=10;
h=(b-a)/N;

% Slope function

%f = inline('t+y','t','y');
%sol = inline('2*exp(t)-t-1','t');

f = inline('t^2+y','t','y');
sol = inline('-2-2*t-t^2+3*exp(t)','t');

% Initial Condition
t(1)=0;
y(1)=1;

% RK2 Method
y1(1)=1;
for i=2:N+1
    k1=h*f(t(i-1),y1(i-1));
    k2=h*f(t(i-1)+h/2,y1(i-1)+k1/2);
    y1(i)=y1(i-1)+k2;
    t(i)=t(i-1)+h;
    end
Err1 = abs(y1(N+1)-sol(1))

[t2,y2]=ode23(f,[0 1],1);
Err2 = abs(y2(end)-sol(1))

tspan=0:h:1;
[t3,y3]=ode23(f,tspan,1);
Err3 = abs(y3(end)-sol(1))

for i=1:N+1
    disp([num2str(sol(t(i))) ' & ' num2str(y1(i)) ' & ' num2str(sol(t(i))-y1(i)) ' & ' num2str(y3(i)) ' & ' num2str(sol(t(i))-y3(i)) '\\' ]) %    ])
end