MATLAB: Runge-Kutta 3

errorsMATLABrunge kutta

So I'm doing a project for school, where i have to solve the x''-x'-x=sin(t) equation with Runge-Kutta.
intervalmin=0;
intervalmax=1;
numnodes=5;
f=@(t,x) [x(2); x(2)+x(1)+sin(t)];
inival=0;
h=0.1;
t=zeros(1,numnodes);
t(1)=intervalmin;
x=zeros(1,numnodes);
X=zeros(1,numnodes);
x(1)=inival;
X(1)=inival;
for i = 2:numnodes
k1 = f(t(i-1),x(i-1));
k2 = f(t(i-1)+h/2,x(i-1)+(h/2)*k1);
k3 = f(t(i-1)+h,x(i-1)-h*k1+2*h*k2);
x(i)=(x(i-1)+h/6)*(k1+4*k2+k3);
X(i)=(X(i-1)+h/6)*((f(t(i-1),X(i-1)))+4*(f(t(i-1)+h/2,X(i-1)+(h/2)*k1))+(f(t(i-1)+h,X(i-1)-h*k1+2*h*k2)));
t(i) = t(i-1)+h;
end
figure
plot(t,x,'.-b',t,X,'-.r');
The code is this so far, but it has multiple errors like:
Index exceeds the number of array elements (1).
Error in Untitled5>@(t,x)[t(2);t(2)+t(1)+sin(x)]
Error in Untitled5 (line 14) k1=f(t(i-1),x(i-1));
I'm pretty new to matlab, and just can't seem to find a way to make it work.

Best Answer

Here is the mistake
SOlution