%%%%%Euler's method for the one-dimensional ODE
%%Set up time mesh:
nn = 5;
dt = 10^(-nn);  %%time steps
tf = 1;  %%time to end run
T = [0:dt:tf]';
n = length(T )-1; %%number of steps

%%Also define analytic, exact solution evaluate at the time points T
x0 = pi/2;
C = log(abs(tan(x0/2)));
X_exact = 2*acot(exp(-(T+C)));

%%Define right hand side (i.e. the vector field of the ODE)
f = @(x) sin(x);

% %%Anoter ode xdot = 1+x^2, x(0) = 0;%%%Cautionary tale, using numerics when
% %existence breaks down!!!
% x0 = 0.0;
% C = atan(x0)
% X_exact = tan(T+C);
% %%Define right hand side (i.e. the vector field of the ODE)
% f = @(x) 1+x.^2;

%%Set up solution vector
X = zeros(n+1,1);



%%Define initial condition and insert as first entry in solution vector

X(1) = x0;

%%time-stepping/marching loop
xold = X(1);
for ii = 1:n
    xnew = xold + f(xold)*dt; %Euler step
    X(ii+1) = xnew; %%store step in solution vector
    xold = xnew; %%update xold for next step
end

Error = abs(X(end) - X_exact(end))

%%Plot solution against exact solution
figure(1)
plot(T,X,'-o',T,X_exact,'LineWidth',2)
xlabel('time t')
ylabel('x')
legend(['Euler method'], ['Exact Solution'])
drawnow;
    
    
  




