# Index exceeds number of array elements (1) Heuns method

3 views (last 30 days)
Darren Tharby on 24 Feb 2021
Answered: VBBV on 20 Nov 2021
% step size %
h = 0.1;
% number of steps %
N = 10;
x(1) = 0.1;
y(1) = 1.1;
f = 2*sin(x)+y;
for i = 1:N
y(i+1) = y(i) + (h/2) * f(x(i),y(i)) + f(x(i+1),y(i+1)),
y(i) + h * f(x(i),y(i));
x(i+1) = x(i)+h;
end
plot(x,y)

KALYAN ACHARJYA on 24 Feb 2021
Edited: KALYAN ACHARJYA on 24 Feb 2021
h = 0.1;
% number of steps %
N = 10;
y=zeros(1,N);
x=zeros(1,N);
x(1) = 0.1;
y(1) = 1.1;
f =@(x,y) 2*sin(x)+y;
for i = 1:N
c1=f(x(i),y(i));
c2=f(x(i)+h,y(i)+c1*h);
y(i+1)=y(i)+(h/2)*(c1+c2);
x(i+1)=x(i)+h;
end
plot(x,y)
##### 1 CommentShowHide None
Darren Tharby on 24 Feb 2021
Thankyou

VBBV on 20 Nov 2021
% step size %
h = 0.1;
% number of steps %
N = 10;
x = zeros(1,N);
y = zeros(1,N);
yt = zeros(1,N);
x(1) = 0.1;
y(1) = 1.1;
f = @(x,y) 2*sin(x)+y;
for i = 2:N
yt(i) = y(i-1) + h * f(x(i-1),y(i-1)); % intermediate approximation
y(i) = y(i-1) + (h/2) * (f(x(i-1),y(i-1)) + f(x(i-1),yt(i)));
x(i) = x(i-1)+h;
end
plot(x,y,'linewidth',2);
hold on;
plot(x,yt,'ro','MarkerSize',6,'MarkerFaceColor','red')
legend('Final approx','Intermediate approx') You have to modify the intermediate values step to get final approximation,