f = @(t,x) -x;
fx = @(t,x) -1;
M = 5;
x_exact = @(t) exp(-t);
x_approx = zeros(2,M);
for N = 1:M
dt = 10^(-(N-1));
t = 0:dt:1;
x = zeros(2,length(t));
x(:,1) = 1;
for i = 1:length(t)-1
x(1,i+1) = x(1,i)+dt*f(t(i),x(1,i));
x(2,i+1) = x(2,i)+dt*f(t(i),x(2,i))+0.5*dt^2*(fx(t(i),x(2,i))*f(t(i),x(2,i)));
end
x_approx(:,N) = x(:,end);
end
loglog(10.^-(1:M),abs(x_approx(1,:)-x_exact(1)),10.^-(1:M),abs(x_approx(2,:)-x_exact(1)))
fitlm(-(1:M),log10(abs(x_approx(1,:)-x_exact(1))))
fitlm(-(1:M),log10(abs(x_approx(2,:)-x_exact(1))))