Help with Lagrange Interpolation: How can I graph the polynomial of my data sett?
2 次查看(过去 30 天)
显示 更早的评论
I am attempting to use Lagrange interpolation to find the polynomial for my data set. How can I alter my code to do this? Below is the code so far, but it only plots the points:
x = [1900 1910 1920 1930 1940 1950 1960 1970 1980 1990 2000 2010];
y = [76.21 92.23 106.0 123.2 132.2 151.3 179.3 203.3 226.5 248.8 281.4 308.7];
disp([x; y])
u = 1880:2020:12.25;
v = polyinterp(x,y,u);
plot(x,y,'o',u,v,'r-');
function v = polyinterp(x,y,u)
n = length(x);
v = zeros(size(u));
for k = 1:n
w = ones(size(u));
for j = [1:k-1 k+1:n]
w = (u-x(j))./(x(k)-x(j)).*w;
end
v = v + w*y(k);
end
end
0 个评论
回答(1 个)
Deepak
2024-8-30
Hi @emma, from my understanding, you are using Lagrange’s Interpolation method to find the polynomial of the given data set. However, the “plot” method only plots the given data points and not the “interpolated polynomial”.
Upon investigating the code, the issue seems to be that the range of interpolation “u” is not defined correctly. The correct range should be the following:
% The range for interpolation
u = 1880:12.25:2020;
Here, the first value (1880) denotes starting value of the sequence, the middle value (12.25) denotes the step size, and the last value (2020) denotes the end of the sequence.
Also, you can add labels, a title, and a legend in the plot to make it more informative.
Here is the documentation of “plot” method in MATLAB for reference:
Below is the complete MATLAB code with the changes:
x = [1900 1910 1920 1930 1940 1950 1960 1970 1980 1990 2000 2010];
y = [76.21 92.23 106.0 123.2 132.2 151.3 179.3 203.3 226.5 248.8 281.4 308.7];
% Display the data points
disp([x; y]);
% Define the range for interpolation
u = 1880:12.25:2020;
% Perform Lagrange interpolation
v = polyinterp(x, y, u);
plot(x, y, 'o', u, v, 'r-');
xlabel('Year');
ylabel('Population (millions)');
title('Lagrange Interpolation of Population Data');
legend('Data Points', 'Interpolated Polynomial', 'Location', 'NorthWest');
% Lagrange interpolation function
function v = polyinterp(x, y, u)
n = length(x);
v = zeros(size(u));
for k = 1:n
w = ones(size(u));
for j = [1:k-1 k+1:n]
w = (u - x(j)) ./ (x(k) - x(j)) .* w;
end
v = v + w * y(k);
end
end
Attaching the documentation of colon operator applications for reference:
I hope this solves the problem.
0 个评论
另请参阅
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!