% This file executes Euler's method for a 1st-order ODE


clear all

h = .2;                 % Choose the step size

x0 = 0;                 % Choose initial x value
xf = 1.;                % Choose the final x value. (Note that xf - x0 must
                        % be divisible by h in order to end exactly at xf)

X = x0:h:xf;            % This makes a list of equally spaced x values from x0 to xf
                        % of step size h
N = length(X);          % We will use the length of the vector of x values
Y = zeros(size(X));     % Preallocates space for y values


Y(1) = 1;               % Choose initial y value


for j = 1:N-1           % a "for" loop, with the index j running from 1 to N-1 
    k = frhs(X(j),Y(j)); % The funtion on the RHS of the DE "frhs" is
                        % the slope function f(x,y). Here we use X(j) for x
                        % and Y(j) for y. This determines the slope of the
                        % tangent line along which the approximation will
                        % step. The function f(x,y) is assumed to be in a separate .m
                        % file called frhs
           
    Y(j+1) = Y(j) + k*h;    % Approximate y value given the last one using 
                            % slope we just calculated and the step size h.
end



Yexact = exp(X);  % This is the exact solution for the DE y'(x)=y.
                  % if you change DE's you will have to change the exact
                  %solution too!  (If you can find one.)

figure(1)

plot(X,Yexact, X, Y)
legend('Exact solution', 'Approximated solution')

error = abs(Yexact(N) - Y(N))
relerror = error/abs(Yexact(N))