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 个评论
回答(1 个)
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.
![](https://www.mathworks.com/matlabcentral/answers/uploaded_files/315630/image.png)
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.
另请参阅
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!