MATLAB: Index out of bounds

out of bounds

I get an error: x2(2): out of bound 1. The same goes for x4(2). What is it about and how can i fix this?
if true
% code
end%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 need to do preallocation for vectors.
f=@(x,y)-y
a=0;
b=8;
h=0.5;
h2=1/16;
x1=zeros(1,17);x2=zeros(1,17);x3=zeros(1,129);x4=zeros(1,129);
y1=4*ones(1,17);y2=4*ones(1,17);y3=4*ones(1,129);y4=4*ones(1,129);
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');
Related Question