MATLAB: How to plot the analytic solution as the numerical solution from Forward Euler and Backward Euler (BE) Method

analytic solution for odesnumerical methods for odes

dx/dt = r*x
dt=0.1; % set the time step
T=50; % set the time duration
Niter = ceil(T/dt); % determine the number of iterations
x = zeros(Niter,1); % preallocate the solution array
x(1)=2000; % set the initial value
t = zeros(Niter,1); % preallocate the time array
r=-0.5; % set the growth rate
So how to plot its analytic solution (x=2000*exp(r*(t – 1)))? Furthermore, how to plot analytic solution given Backward Euler (x(i+1) = x(i)/(1-r*dt);t(i+1) = t(i) + dt)?

Best Answer

% dx/dt = r*x
dt=0.1; % set the time step
T=50; % set the time duration
Niter = ceil(T/dt); % determine the number of iterations
x = zeros(Niter,1); % preallocate the solution array
x(1)=2000; % set the initial value
r=-0.5; % set the growth rate
t = 0:dt:T ;
x1 = @(r,t) 2000*exp(r*(t - 1)) ;
x1 = x1(r,t) ;
% Loop
x2 = zeros(size(t)) ;
x2(1) = 2000 ;
for i = 2:length(t)
x2(i) = x2(i-1)/(1-r*dt);
end
figure
hold on
plot(t,x1,'r')
plot(t,x2,'b')
legend('analytical','Euler')
Related Question