h = .2; eul_vect = []; rk2_vect = []; rk4_vect = []; h_vect = {};
t = 0: .05:3;
y = -t - 1 + 2*exp(t);
for k=1:8
[teuler, yeuler] = eul(@yplust1,[0,3],1,h);
[trk2,yrk2] = rk2(@yplust1,[0,3],1,h);
[trk4,yrk4] = rk4(@yplust1,[0,3],1,h);
plot(t,y,teuler,yeuler,'.',trk2,yrk2,'+',trk4,yrk4,'x')
legend('Exact','Euler','RK2','RK4',2)
shg
zeuler = -teuler - 1 + 2*exp(teuler);
eulerror = max(abs(zeuler - yeuler));
zrk2 = -trk2 - 1 + 2*exp(trk2);
rk2error = max(abs(zrk2 - yrk2));
zrk4 = -trk4 - 1 + 2*exp(trk4);
rk4error = max(abs(zrk4 - yrk4));
h_vect = [h_vect,h]
eul_vect = [eul_vect,eulerror]
rk2_vect = [rk2_vect,rk2error]
rk4_vect = [rk4_vect,rk4error]
pause
h = h/2;
end
loglog(h_vect,eul_vect,h_vect,rk2_vect,h_vect,rk4_vect)
legend('eul','rk2','rk4',4)
grid, xlabel('Step size'),ylabel('Maximum error')
title('Maximum error vs. step size'), axis tight