Forward, backward and modified Euler methods; plots do not come as usual, HELP
Afficher commentaires plus anciens
clear all;
close all;
clc
%y'=4y (y'=dYdt in the code)
%t=0 to t=3
%y(0)=1
%y=exp(4t)
t0=0; %initial time
tf=3; %final time
dt=0.01; %step size
t=t0:dt:tf; %indep variable - time
y(1)=1; %initial cond for forward euler
y2(1)=y(1); %initial cond for backward euler
ym(1)=y(1); %initial cond for mod euler
yex(1)=y(1); %exact y value at t=0
for i=1:length(t)-1
dYdt(i)=4*y(i);
y(i+1)=y(i)+dt*dYdt(i); %Forward euler eqn
dYdt(i+1)=4*y(i+1);
y2(i+1)=y(i)+dt*dYdt(i+1); %Backward euler eqn
ym(i+1)=y(i)+(dYdt(i)+dYdt(i+1))*0.5*dt; %Modified euler eqn
yex(i+1)=exp(4*t(i+1)); %Exact eqn
end
figure(1)
hold on
plot(t,y,'ro') % plot of forward E.
plot(t,y2,'bo') % plot of backward E.
plot(t,ym,'mo') % plot of mod E.
plot(t,yex,'Linewidth',1.2) %plot of exact fun.
xlabel('time (s)')
ylabel('y(t)')
title('For/Backward & Modified Euler vs. Exact solution')
legend('Forward Euler','Backward Euler','Modified Euler','Exact solution')
hold off
I want to know whether there is any error in this and not another method to the same thing. Thanks!
2 commentaires
madhan ravi
le 14 Juin 2020
Preallocate variables.
Poojitha Ariyathilaka
le 14 Juin 2020
Modifié(e) : Poojitha Ariyathilaka
le 14 Juin 2020
Réponses (1)
The solution of numerical model depends on the number of discretization. The more the discretization (time step dt here) the close your solution will be to analytical. Try changing the time step. Try
dt = 0.001 ;
You can do a parametric study, take different time steps and see.

Note: You need to initialize the solution i.e the variables which are inside loop and you are saving. They should be initilaized. Read about initializing.
1 commentaire
Poojitha Ariyathilaka
le 14 Juin 2020
Catégories
En savoir plus sur Mathematics dans Centre d'aide et File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!