MATLAB: I know in matlab, index start from 1, not 0; How come I get an error on line k1 saying index exceeds matrix dimension even though for loop starts from 2

MATLABmatrix array

real x1;
real x2;
span=[0,4];
h=.04;
x10=0;
x20=1;
x1(1)=x10;
x2(1)=x20;
step= 100;
f=@(x1,x2) -3*x2;
f1=@(x1,x2)(1/3)*x1;
for j=2:step
x1(j,1)=x1(j-1)+h;
k1(j-1,1)=h*f( x1(j-1), x2(j-1)); % index exceeds matrix dimension
k2(j-1,1)=h*f( x1(j-1)+h/2, x2(j-1)+0.5*k1(j-1) );
k3(j-1,1)=h*f( x1(j-1)+h/2, x2(j-1)+0.5*k2(j-1) );
k4(j-1,1)=h*f( x1(j-1)+h, x2(j-1)+k3(j-1) );
y1(j,1)=x2(j-1)+(1/6)*(k1(j-1)+2*k2(j-1)+2*k3(j-1)+k4(j-1));
end

Best Answer

Because you did not do any preallocation for k1, k2, k3 and k4. Add this code before your loop and after the definition of step:
k1=zeros(step-1,1)
k2=zeros(step-1,1)
k3=zeros(step-1,1)
k4=zeros(step-1,1)
y1=zeros(step,1)
Related Question