%% Euler's Method
% Solves the initial value problem y'= x + y, y(x0)=y0 

clc, clear all, close all
%% 
% Define the RHS of the ODE
f=@(t,y) t*exp(3*t)-2*y; 
fprime=@(t,y) exp(3*t)+3*t*exp(3*t)-2*f(t,y);
% Initial values
t0=0; y0=0;
% Final value of x
tf=1;
% Step size, 
h=0.1; 
% number of steps
N=floor((tf-t0)/h);

%%
t=t0; y=y0;
T=t0; Y=y0; % stores the initial values
hold on

for i=1:N
    y = y + h*[f(t,y)+h/2*fprime(t,y)];
    t = t + h;
    
    plot(t,y,'o') % plots the computed approximation
    
    T=[T;t]; Y=[Y;y]; % stores all computed values 
end
grid on
xlabel('t'); ylabel('y')
title('Euler Method')

disp('      T          Y')
disp([T Y])


% %% 
% % If an explicit solution can be found, it can eb entered below
% % for comparing it with the approximate solution, otherwise
% % the entire code below must be commented out! 
% yexact = @(x) -x-1+2*exp(x);
% % Plot of the exact solution for comparison purposes only
% fplot(yexact, [x0 xf],'Color','r')
% hold off

