MATLAB: Error: Index exceeds the number of array elements(1)

index-errorMATLAB

Whenever I run the below modified euler solver for the second order differential equation, an error comes up. How can I solve this please ? Attached find the main script and the function for the 2 first order differentials which the second order differential was split into. Many Thanks
%main script
t0 = 0;
tf = 20;
h = 0.0001;
t = (t0:h:tf);
v0 = 1;
v1= v0;
x0 = 0;
x1 = x0;
n =length(t);
for i = 1 : n-1
x1temp = x1(i) + fofx1(x1(i), x2(i))*h;
avedv1dt = (fofx1(x1(i), x2(i)) + fofx1(x1temp ,x2(i+1)))/2;
x1(i+1) = x1(i) + avedv1dt*h;
v1temp = v1(i) + fofv1(v1(i))*h;
avedx1dt =(fofv1(v1(i)) + fofv1(v1temp))/2;
v1(i+1) = v1(i) + avedx1dt*h;
end

Best Answer

your x1 and x2 start out scalar. When i is 1 you access x1(1) and x2(1) no problem and you create x1(2). Then i=2 you access x2(2) which works, and x2(2) which fails because you did not assign x2(2)