clear all;
close all;
Delta_t=1.0;
t=0:Delta_t:8.0;
%Preallocating memory
x=zeros(size(t));
%Initial condition
x(1)=0.0;
for n=1:length(t)-1
k1=f(t(n),x(n));
k2=f(t(n)+Delta_t/2,x(n)+Delta_t*k1/2);
k3=f(t(n)+Delta_t/2,x(n)+Delta_t*k2/2);
k4=f(t(n)+Delta_t,x(n)+Delta_t*k3);
x(n+1)=x(n)+(Delta_t/6)*(k1+2.0*(k2+k3)+k4);
end
plot(t,x,’ko-‘,’linewidth’,2,’Markersize’,10)
hold on
tplot=0:0.01:8.0;
truesolution=@(t)(1-exp(-t))
plot(tplot,truesolution(tplot),’b-‘,’linewidth’,2)
xlabel(‘t’);
ylabel(‘x’);
legend(‘RK-4′,’True’);
axis([0 8 0 2])
function dxdt=f(t,x)
dxdt=1-x;
end