index exceeds the number of array elements at y2 for the finite difference formulas
1 次查看(过去 30 天)
显示 更早的评论
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
0 个评论
采纳的回答
Ameer Hamza
2020-4-2
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
更多回答(0 个)
另请参阅
类别
在 Help Center 和 File Exchange 中查找有关 Matrix Indexing 的更多信息
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!