%% Euler's method for ODE, first example
%  
% IVP:  y'=t+y, y(0)=1
% Manually stepping ("uparrow-iteration")
clear close all
%% Analytic solution easy in this case:
syms y(t) 
Dy = diff(y);
dsolve(Dy == t+y, y(0) == 1)
%{
ans = 
2*exp(t) - t - 1   % Exact analytic sol.
yanal=@(t)2exp(t) - t -1}
 %}
%% Define anal sol as a function handle:
  yanal=@(t)2*exp(t) - t -1
  
%% Numeric sol.     y'=t+y,y(0)=1, sol. on [0,1.2]         
clear; close all
f=@(t,y) t+y
YL=[]   % Cumulate approximations in Y, start with empty.
n=1;
%% Execute this cell repeatedly:  (CTR-ENTER):
n=2*n,[T,Y]=eulerS(f,[0 1.2],1,n);
hold on;grid on
[T Y];plot(T,Y,T,Y,'.r');shg;
YL=[YL; Y(end)]
%% After iteration:
ezplot(yanal,[0,1.2]) %Plot-options don't work for ezplot or fplot
%%
t=linspace(0,1.2);
plot(t,yanal(t),'k','LineWidth',2);shg

format compact
%%
clc
['Endpoint t   Exact sol.  Euler-approksimation']
[T(end) yanal(T(end)) YL(end)]
%%
endpointerrors=yanal(T(end))-YL
%%
% Change n=2*n to see: Error is O(h) (error is halved with stepsize)
% Slow but easy to understandm starting point for all more
% developed numerical methods for ODE's.