Skip to content

Commit 53185b2

Browse files
vasilisk075jiegillet
authored andcommitted
euler.m (#158)
Matlab implementation of the Forward Euler method
1 parent 0f5367f commit 53185b2

File tree

1 file changed

+46
-0
lines changed
  • chapters/differential_equations/euler/code

1 file changed

+46
-0
lines changed
Lines changed: 46 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,46 @@
1+
clc;clear;close all
2+
3+
%==========================================================================
4+
% Define Function
5+
f =@(x) -3*x;
6+
7+
% Define Initial and Final time
8+
tInit=0;
9+
tLast=5;
10+
11+
% Define number of points
12+
N=1e2;
13+
14+
% Set Initial Conditions
15+
yInit=1;
16+
%==========================================================================
17+
18+
dt=(tLast-tInit)/(N-1); % Calculate dt
19+
t=[tInit:dt:tLast]; % Preallocate time array
20+
y=zeros(1,length(t)); % Preallocate solution array
21+
y(1)=yInit; % Impose Initial Conditions
22+
23+
% Loop over time
24+
for i=1:length(t)-1
25+
26+
t(i+1) = t(i) + dt; % Calculate next time
27+
y(i+1) = y(i) + f( y(i) )*dt; % Update solution
28+
29+
end
30+
31+
% Plot numerical solution
32+
plot(t,y)
33+
34+
% Create analytical solution
35+
g=@(x) exp(-3*x);
36+
z=g(t);
37+
38+
% Plot analytical solution on the same graph
39+
hold on
40+
plot(t,z,'--')
41+
42+
% Set axis, title and legend
43+
xlabel('t');ylabel('y(t)');
44+
title('Analytical VS Numerical Solution')
45+
grid
46+
legend('Numerical','Analytical')

0 commit comments

Comments
 (0)