Skip to content

euler.m #158

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 2 commits into from
Jul 1, 2018
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
46 changes: 46 additions & 0 deletions chapters/differential_equations/euler/code/euler.m
Original file line number Diff line number Diff line change
@@ -0,0 +1,46 @@
clc;clear;close all

%==========================================================================
% Define Function
f =@(x) -3*x;

% Define Initial and Final time
tInit=0;
tLast=5;

% Define number of points
N=1e2;

% Set Initial Conditions
yInit=1;
%==========================================================================

dt=(tLast-tInit)/(N-1); % Calculate dt
t=[tInit:dt:tLast]; % Preallocate time array
y=zeros(1,length(t)); % Preallocate solution array
y(1)=yInit; % Impose Initial Conditions

% Loop over time
for i=1:length(t)-1

t(i+1) = t(i) + dt; % Calculate next time
y(i+1) = y(i) + f( y(i) )*dt; % Update solution

end

% Plot numerical solution
plot(t,y)

% Create analytical solution
g=@(x) exp(-3*x);
z=g(t);

% Plot analytical solution on the same graph
hold on
plot(t,z,'--')

% Set axis, title and legend
xlabel('t');ylabel('y(t)');
title('Analytical VS Numerical Solution')
grid
legend('Numerical','Analytical')