Matlab使用fzero向后欧拉 [英] Matlab backward Euler using fzero
问题描述
我正在尝试整合dy3dt = @(t,y)-41 *(y-t)+ 1;使用后向Euler在h = 0.05时超过[0,1].初始条件y(0)为1.
I am trying to integrate dy3dt = @(t,y) -41*(y - t) + 1; over [0, 1] with h = 0.05 using backward Euler. The initial condition, y(0) is 1.
yvals3 = [1]; %inital condition
dy3dt = @(t,y) -41*(y - t) + 1;
for t = 0:0.05:0.95;
index = round(t*20 + 1); %convert t into index of the last step
oldy = yvals3(index);
newy1 = oldy + h.*dy3dt(t, oldy);
newy2 = oldy + h.*dy3dt(t+ 0.05, newy1);
yvals3 = [yvals3; newy2];
end
tvals3 = 0:0.05:1;
当我绘制tvals3和yvals3的图形时,我得到了一个不寻常的指数图,所以我的方法可能不正确.关于如何使用fzero实现此功能的任何见解?
When I graph tvals3 and yvals3, I am getting an unusual exponential graph, so my approach is probably incorrect. Any insight on how to implement this using fzero?
推荐答案
通常的(向前)欧拉方法可以表示为从切线上的已知点开始并获得新点:
The usual (forward) Euler's method can be expressed as going from a known point on a tangent, and getting new point:
newy = oldy + tstep*dydt(oldt, oldy);
向后Euler方法向后进行所有操作:它从切线上的一个新点(至今未知)开始向后,并到达了旧点:
The backward Euler method does everything backwards: it goes from a new (yet unknown) point on a tangent, backward, and hits the old point:
oldy = newy - tstep*dydt(newt, newy);
最后一行不是可以执行的命令,因为newy
是未知的.相反,这是一个需要解决的方程式:
This last line is not a command that can be executed, since newy
is unknown. Instead, it's an equation to be solved:
newy = fzero(@(y) y - tstep*dydt(newt,y) - oldy, oldy)
(第二个参数oldy
是对fzero
所需的根的初始猜测.)
(The second parameter, oldy
, is an initial guess to the root, which fzero
needs.)
这是在您的设置中可以使用的方式.我写的代码可能不是最高效的Matlab,但是(希望)可以使计算逻辑清晰明了.
Here's how this could work in your setup. I wrote the code in a way that may not be the most Matlab-efficient, but (I hope) makes the logic of computation clear.
dydt = @(t,y) -41*(y - t) + 1; % right hand side
tvals = [0]; % initial t
yvals = [1]; % initial y
tstep = 0.05; % time step
numsteps = 20; % number of steps to go
for i=1:numsteps;
oldt = tvals(end); % pick the last entry of array
oldy = yvals(end);
newt = oldt + tstep; % step forward in t
newy = fzero(@(y) y - tstep*dydt(newt,y) - oldy, oldy); % backward Euler
tvals = [tvals; newt];
yvals = [yvals; newy];
end
plot(tvals, yvals);
这篇关于Matlab使用fzero向后欧拉的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!