Why doesn't my backward Euler-method end up with the same result as ODE45?

2 views (last 30 days)
I won't end up with the same result when using this backward euler method as when using ode45, I want to believe that my code is correct. But obviously it isn't. Would be very grateful for some advice concerning the code below.
function [t,U]=backwardEuler(f,I,U0,N)
t=linspace(I(1),I(2),N+1); %Generates time nodes(?)
U=zeros(1,size(t,2)); %Vector in which the solution is saved
U(1)=U0; %u0
k=t(2)-t(1); %Step size
tol=k^2; %Fixedpoint tolerance
for n=2:N+1
Uguess=U(n-1); % First guess, previous value
g=@(x)(U(n-1)+(k*f(t(n),U(n)))); % Fixedpoint function changes every lap.
U(n)=fixedpoint(g, Uguess , tol);
end
U=U'; % Same form as ode45...
t=t'; % Same form as ode45...
-------- fixedpoint -------
function x=fixedpoint(f, Uguess , tol)
x=Uguess;
while abs(f(x)-x)>tol
x=f(x);
end
-------- f ------
function y=f(x,t)
y=-x-(t^2);

Answers (0)

Community Treasure Hunt

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

Start Hunting!