%% Euler's method for y'=t+y, y(0)=1 on [0,4], Eulerloop.m
% 
%   Change the manual iteration to an interactive while-loop.
%   (Can't "publish" when using interactive "input")
%% Function handles:
%
clear; close all;clc
% Function defining the diff. equ: [y' = f(t,y)]
f=@(t,y)t+y
%
% Exact solution: (By hand or symbolic toolbox: help dsolve)
syms y(t)
dsolve(diff(y)==t+y,y(0)==1)
%% Define as a function
yanal=@(t) 2*exp(t) - t -1
%% Just check: (you can skip this now)
syms t
y=2*exp(t) - t -1
diff(y,t) == y+t    % Diff equ satisfied
subs(y,t,0)         % initial condition, too
%%
clear t y   % Safety measure
%% One trial call.
Yend=[]   % Cumulate approximations at enpoint
n=3;
[T,Y]=eulerS(f,[0 4],1,n); [T Y],plot(T,Y,T,Y,'.r');shg;Yend=[Yend;Y(end)]
grid on; hold on
%% Now in loop (interactive):
while 1     % Infinite loop (1 is always true), let user break it.
   n=2*n
   [T,Y]=eulerS(f,[0 4],1,n); 
   plot(T,Y,T,Y,'.r');shg;
   Yend=[Yend; Y(end)]
   reply=input('Continue? Y/N [Y]:','s');
   if isempty(reply)
       reply='Y'
   end    
   if upper(reply)=='N'
       break
   end
   if n > 200  % A safety check in case user gets out of mind.
       break
   end    
end  
%% 
t=linspace(0,4);
plot(t,yanal(t),'k','LineWidth',2)
disp(['  ','Final t | Exact sol.|Euler-approksimation'])
disp([T(end) yanal(T(end)) Yend(end)])
endpointerrors=yanal(T(end))-Yend;
%%
[diff(endpointerrors);NaN];
[endpointerrors [diff(endpointerrors);NaN]]
