Help with Lagrange Interpolation: How can I graph the polynomial of my data sett?

2 vues (au cours des 30 derniers jours)
emma
emma le 10 Avr 2021
Réponse apportée : Deepak le 30 Août 2024
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

Réponses (1)

Deepak
Deepak le 30 Août 2024
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]);
1.0e+03 * 1.9000 1.9100 1.9200 1.9300 1.9400 1.9500 1.9600 1.9700 1.9800 1.9900 2.0000 2.0100 0.0762 0.0922 0.1060 0.1232 0.1322 0.1513 0.1793 0.2033 0.2265 0.2488 0.2814 0.3087
% 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.

Catégories

En savoir plus sur Interpolation dans Help Center et File Exchange

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!

Translated by