Did I implement the backwards-euler Methode correctly?

58 次查看(过去 30 天)
Hello everyone :)
I struggle a little bit with Backwards Euler Method and an excercise our professor gave us:
With h (step size between two adjacent points) = 1/49
Our Task is to plot this. I tried with my Backwards-euler script:
function [t,y] = Euler_backward(t0,T,y0,h,f)
%h = (T-t0)/m ; %I usually let him calculate h but since it is given I have percentaged(?) it out
t = t0:h:T ; % my time vector
y = zeros(length(y0), length(t)) ; % To be able to calculate a system, I want it to make a matrix with y0 rows and t columns
y(:,1) = y0 ;
for i = 2:length(t)-1
ye(:,i) = y(:,i) + h * f(t(i),y(:,i)) ; % forward Euler Method : y(i+1) = y(i) + h*f(t(i),y(i)) to provide y(i+1) for backwards
y(:,i+1) = y(:,i) + h*f(t(:,i),ye(:,i)) ; % Backwards part with y(i+1) = y(i) + h*f(t(i+1),y(i+1))
end
plot(t,y)
legend('y1','y2')
end
and my separate script (I like to separate script and function):
t0 = 0;
T = 1;
y0 = [1;1]; %Starting conditions
f =@(y,t) [0*y(1)+1*y(2);... %Made a function from the matrix
-101*(y1)-100*y(2)];
h = 1/49 ;
Euler_backward(t0,T,y0,h,f)
It then gives me following graph:
mlsg.jpg
and the graph from our professor looks like this:
I didn't graph the solutions but it is pretty clear, that my solution hardly resembles the solution of my professor.
Now I am kinda lost where my mistake is. Did I implement the backwards euler wrong? It would be very kind if someone could help with this :)
Have a great day,
Marcus
  2 个评论
darova
darova 2019-11-29
How does it work?
y = zeros(length(y0), length(t)) ; % To be able to calculate a system, I want it to make a matrix with y0 rows and t columns
Why do you need 2D matrix?
Marcus Schlitter
Marcus Schlitter 2019-12-7
Sorry for the late answer.
I wanted to make a zero matrix to make place for the different ys. So the first column would consist of the y0 values and then for every step the next column is filled. Is this step unecessary?

请先登录,再进行评论。

采纳的回答

Devineni Aslesha
Devineni Aslesha 2019-12-5
Hi Marchus,
The backward euler method is implemented correctly, however as f is not a function of t, the plot is constant for increasing t values. Also, f can be updated as shown below.
A = [0 1; -100 -101];
f=@(t,y) A*y;

更多回答(0 个)

类别

Help CenterFile Exchange 中查找有关 2-D and 3-D Plots 的更多信息

产品

Community Treasure Hunt

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

Start Hunting!

Translated by