%% Eulerexample 1
%%
% 
% $$y'= t+y, y(0)=0$$
% 
% yexact=exp(t)-t-1
clear; close all;format compact
%% Case a) h=0.4
h=0.4; n=3;
ta=(0:h:n*h)'; % Column vector
ya=zeros(n,1); % Allocate a column vector (not necessary for small problems).
ya(1)=0;       % Initial value 0, Matlab indexing starts with 1.
for k=1:n
    ya(k+1)=ya(k)+h*(ta(k)+ya(k));  % Euler step.
end;
[ta ya]
plot(ta,ya,'r',ta,ya,'ko');grid on
title(['Euler''s method, y''=t+y, y(0)=0)']);
hold on
%% b)  h=0.2
h=0.2; n=6;
tb=0:h:n*h;
yb(1)=0;   
for k=1:n
    yb(k+1)=yb(k)+h*(tb(k)+yb(k));
end;
[tb;yb]
plot(tb,yb,'g',tb,yb,'ko')

%% c) h=0.1
h=0.1; n=12;
tc=0:h:n*h;
yc(1)=0;   
for k=1:n
    yc(k+1)=yc(k)+h*(tc(k)+yc(k));
end;
[tc;yc]
plot(tc,yc,'b',tc,yc,'bx')
% legend('n=3','n=3','n=6','n=6','n=12','n=12')

Yfinal=[ya(end);yb(end);yc(end)]
Tfinal=ta(end)   % ==tb(end) == tc(end)
%%
yexactFinal=exp(Tfinal)-Tfinal-1 
%%
errors=yexactFinal-[ya(end);yb(end);yc(end)]
%%
diff(errors)
