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

조회 수: 6 (최근 30일)
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
Poojitha Ariyathilaka
Poojitha Ariyathilaka 2020년 6월 14일
편집: Poojitha Ariyathilaka 2020년 6월 14일
I didn't get the point, could you please point me the lines. Would preallocating resolve the aroused problem?

댓글을 달려면 로그인하십시오.

답변 (1개)

KSSV
KSSV 2020년 6월 14일
편집: KSSV 2020년 6월 14일
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
Poojitha Ariyathilaka
Poojitha Ariyathilaka 2020년 6월 14일
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.

댓글을 달려면 로그인하십시오.

카테고리

Help CenterFile Exchange에서 Ordinary Differential Equations에 대해 자세히 알아보기

제품


릴리스

R2018a

Community Treasure Hunt

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

Start Hunting!

Translated by