MATLAB: Error: x2(2): out of bound 1 ??? what does it mean in the code and how do i change it

out of bound

%Euler.m
clear all, close all, clc
f=@(x,y)-y
a=0;
b=8;
h=0.5;
h2=1/16;
x1(1)=0;
y1(1)=4;
x2(1)=0;
y2(1)=4;
x3(1)=0;
y3(1)=4;
x4(1)=0;
y4(1)=4;
error1=[];
error2=[];
for k=1:16
x1(k+1)=x1(k)+h;
y1(k+1)=y1(k)+h*f(x1(k),y1(k));
y2(k+1)=y2(k)+h*f(x2(k),y2(k));
end
error1=y2-y1;
error1w=error1./y2;
for k=1:128
x3(k+1)=x3(k)+h2;
y3(k+1)=y3(k)+h2*f(x3(k),y3(k));
y4(k+1)=y4(k)+h2*f(x4(k),y4(k));
end
error2=y4-y3;
error2w=error2./y4;
figure
plot(x1, y1, 'r', x3, y3, 'b');
legend('h=0.5','h=1/16');
figure
plot(x1, error1, x3, error2);
legend('h=0.5','h=1/16');
figure
plot(x1, error1w, x3, error2w);
legend('h=0.5','h=1/16');

Best Answer

You have
x2(1)=0;
which creates x2 as a scalar containing a single 0. You have no other code that writes to x2.
You have
for k=1:16
x1(k+1)=x1(k)+h;
y1(k+1)=y1(k)+h*f(x1(k),y1(k));
y2(k+1)=y2(k)+h*f(x2(k),y2(k));
end
For the second iteration of that, when k = 2, the line
y2(k+1)=y2(k)+h*f(x2(k),y2(k));
would be
y2(2+1)=y2(2)+h*f(x2(2),y2(2));
That would require that x2(2) exists. But it doesn't. You wrote to x2(1) but not to any other x2 location.