%% Runge Kutta method %%
%% Written for x'=f(x) with f(x)=-x and x(0)=x0
dt=.1;
x0=1;
t0=0;
endtime=1;
t=0:dt:endtime;
N=(endtime-t0)/dt;
x(1)=x0;
for n=1:N
k1=-x(n)*dt;
k2=-(x(n)+0.5*k1)*dt;
k3=-(x(n)+0.5*k2)*dt;
k4=-(x(n)+k3)*dt;
x(n+1)=x(n)+1/6*(k1+2*k2+2*k3+k4);
end
plot(t,x,'k')
hold on
%% END RUNGE KUTTA METHOD %%
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% For our simple example we can find the real solution:
A=x0; %Define the constant
x_realsoln_final=A*exp(-endtime); %The solution at the last step to calculate error
x_real=A.*exp(-1.*t); %The general Solution
plot(t,x_real,'b')
hold off
Error=abs(x_realsoln_final-x(N+1)) %In this case the error the difference between the real and numerical solutions.
% In general you would skip the step above because you do not know the real solution!
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%