Effacer les filtres
Effacer les filtres

Forward, backward and modified Euler methods; plots do not come as usual, HELP

3 vues (au cours des 30 derniers jours)
Poojitha Ariyathilaka
Poojitha Ariyathilaka le 14 Juin 2020
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
madhan ravi le 14 Juin 2020
Preallocate variables.
Poojitha Ariyathilaka
Poojitha Ariyathilaka le 14 Juin 2020
Modifié(e) : Poojitha Ariyathilaka le 14 Juin 2020
I didn't get the point, could you please point me the lines. Would preallocating resolve the aroused problem?

Connectez-vous pour commenter.

Réponses (1)

KSSV
KSSV le 14 Juin 2020
Modifié(e) : KSSV le 14 Juin 2020
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
Poojitha Ariyathilaka le 14 Juin 2020
I know what happen when step size's altered. My question is not that. Usually the plot of exact equation must come in between backward euler approximation plot and the modified e. approx. plot. Here, the plot of exact eqn lies above all 3 other approximation plots. I want to figure out the reason for this wrong behaviour. i.e Variables have initialized.

Connectez-vous pour commenter.

Catégories

En savoir plus sur 2-D and 3-D Plots dans Help Center et File Exchange

Produits


Version

R2018a

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!

Translated by