MATLAB: Index exceeds the number of array elements at y2 for the finite difference formulas

exceeds the number of array elementsy2(i) is getting and index error

clear; close all; clc;
%% Parameters
f = exp(x);
deltaX = 0.05;
x = 2:deltaX:2.5;
f = exp(x);
n = length(x);
y = zeros(n,1);
y2 = zeros(n,1);
y3 = zeros(n,1);
y4 = zeros(n,1);
y5 = zeros(n,1);
y6 = zeros(n,1);
%% finite difference formulas
for i = 1:n-1
%forward difference - first and second derivative
y(i) = (f(i+1)- f(i))/deltaX;
y2(i) = (f(i+2) - 2*f(i+1) + f(i))/(deltaX.^2);
end
for i = 2:n
%backward difference - first and second derivative
y3(i) = (f(i)- f(i-1))/deltaX;
y4(i) = (f(i) -- 2*f(i-1) + f(i-2))/(deltaX.^2);
end
for i = 2:n-1
%central difference - first and second derivative
y5(i) = (f(i+1)- f(i-1))/(2*deltaX);
y6(i) = (f(i+1) - 2*f(i) + f(i-1))/(deltaX.^2);
end

Best Answer

In this line
y2(i) = (f(i+2) - 2*f(i+1) + f(i))/(deltaX.^2);
index of f is i+2, therefore, i should not go above n. Change the range of the for loop like this
for i = 1:n-2 % change this range
%forward difference - first and second derivative
y(i) = (f(i+1)- f(i))/deltaX;
y2(i) = (f(i+2) - 2*f(i+1) + f(i))/(deltaX.^2);
end
Similarly in the line
y4(i) = (f(i) -- 2*f(i-1) + f(i-2))/(deltaX.^2);
index of f is i-2, so i should not go below 3
for i = 3:n
%backward difference - first and second derivative
y3(i) = (f(i)- f(i-1))/deltaX;
y4(i) = (f(i) -- 2*f(i-1) + f(i-2))/(deltaX.^2);
end
Related Question