% euler_numerical_integration  
                                            % 29.11.2023
% y0: initial value of the solution at t=0 
% delt: time step increment
% tf: final time
% The ODE to be numerically integrated
% is entered as the local function.

% The desired evaluation time of the solution y
% is entered as the time-value  x
% The answer y is given at the nearest integer
% time value of the desired time x 

 close;clc

% Data:
y0 = 100; delt = 0.5; tf = 10; 

% Definitions
t = 0:delt:tf; % time vector
y(1) = y0;     % y0-value assigned to y(1)

% Calculation of "y" using Euler method
for i = 1:length(t)-1
      y(i+1) = y(i) + delt * eqn(t(i));
end

% __________________________________
% y-value at the required time

% Enter the required time
disp('Desired evaluation time (0 - 10):')
x = 5.2;
fprintf('t = %0.1f   [s]\n', x)
disp(' ')
disp('Results')
% Associated index n
disp('Associated index converted to the nearest integer:')
n = x/delt + 1;
% 
% convertion to nearest integer
n = int32(n);
fprintf('n = %.1f   [-]\n', n);

t_index= (n-1)*delt; 
disp('Time used in the evaluation:')
disp('(nearest integer time value)')
fprintf('t_value = %.1f [s]\n', t_index);

% Value of the y-element
disp('y value at the evaluation time:')
val = y(n);
fprintf('y = %.1f [ ]\n', val);


% ________________________________
% Plot

% Show numerical solution "y" in a blue line
plot(t,y,'b'); 
title('Euler'); xlabel('time');ylabel('y')

% Vertival line at n = t_index
xline(t_index)
% Horizontal line at y = val
yline(val)

% Show exact solution in a red colored line
% with dots
hold on  
fplot(@(t)7.*t.^2 -3.*t + 100,[0 10],'r:')

% some next texts must be adjusted to the 
% function requirements
text(0.3,750,'Euler method')
text(0.3,700,'ODE: z = 14 * t - 3 ') 
text(0.3,650,'Solution:') 
text(0.3,600,'y = 7.*t.^2 -3.*t + 100')
text(0.3,550,'Initial conditions')
text(0.3,500,'y(0) = 100') 
text(0.3,450,'x(0) = 0')

text(7.0,100,'Euler solution (blue)')
text(7.0,50,'Exact solution (red)')

% _________ Local function ___________
% z:derivative to be numerically integrated
function z = eqn(t)
  z = 14 * t - 3;
end


