Error in Hermite Polynomial
3 views (last 30 days)
Show older comments
Hermite_Polynomial.m
function Q = Hermite_Polynomial(X, Y, YP)
n = length(X) - 1;
Q = zeros(2*n + 2, 2*n + 2);
for i = 0:n
z(2*i + 1) = X(i + 1);
z(2*i + 2) = X(i + 1);
Q(2*i + 1, 1) = Y(i + 1);
Q(2*i + 2, 1) = Y(i + 1);
Q(2*i + 2, 2) = YP(i + 1);
if i ~= 0
Q(2*i + 1, 2) = (Q(2*i + 1, 1) - Q(2*i - 1, 1)) / (z(2*i + 1) - z(2*i - 1));
end
end
for i = 2:2*n + 1
for j = 2:i
Q(i, j) = (Q(i, j - 1) - Q(i - 1, j - 1)) / (z(i) - z(i - j + 1));
end
end
result = Q(i,j);
end
main.m
clear all
X = [1, 2, 3];
Y = [1.105170918, 1.491824698, 2.459603111];
YP = [0.2210341836, 0.5967298792, 1.475761867];
x_interp = 1.25;
% Compute divided differences
Q = Hermite_Polynomial(X, Y, YP);
% Interpolate using Hermite polynomial
n = length(X) - 1;
result_H5 = Q(1, 1);
for i = 1:2*n+1
Q_ii = Q(i,i);
product = 1;
for j = 0:i-1
Q_ii = Q_ii * (x_interp - X(j));
end
result_H5 = result_H5 + Q_ii;
end
% Compute Hermite interpolation using H3(1.25)
result_H3 = Q(1, 1);
for i = 1:2*n-1
Q_ii = Q(i,i);
product = 1;
for j = 0:i-1
product = product * (x_interp - X(j));
end
result_H3 = result_H3 + Q_ii;
end
% Display results
disp(['H5(1.25) approximation: ', num2str(result_H5)]);
disp(['H3(1.25) approximation: ', num2str(result_H3)]);
The above is my code when I run it I get the error saying the following:
Array indices must be positive integers or logical values.
Error in main (line 15)
z_product = z_product * (x_interp - X(j);
Array indices must be positive integers or logical values.
Error in main (line 29)
product = product .* (x_interp - X(j));
Please help me debug the it
0 Comments
Answers (1)
Alan Stevens
on 20 Aug 2023
Edited: Alan Stevens
on 20 Aug 2023
In line
for j = 0:i-1
you have j starting at zero. Matlab's indices start at 1, so the following line should have X(j+1) not X(j).
0 Comments
See Also
Categories
Find more on Interpolation in Help Center and File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!