Lagrange Interpolation Code Error/Help
3 vues (au cours des 30 derniers jours)
Afficher commentaires plus anciens
Hello! I am to graph an interpolating polynomial and the data points. The data points are from a file which I will provide. I keep running into an error which is "Array indices must be positive integers or logical values." for my variable ys. I would love to use polyval however I am not allowed in this assignment. Any idea how to fix this or what I need to change?? I know that p is not the right thing to do...Thanks in advance!
data file (first line are the x values, second line is the y values, and third line is N which will be the number of points to use to graph the polynomial which is found in xs)
1 2 3 4 5 6 7
1 4 9 16 25 36 49
101
code:
clear;
clf;
%reading from dot_data file
fid = fopen('data_file.m','r');
x = str2num(fgetl(fid)); %reads in first line of data
n = length(x); %length of x
tline = fgets(fid); %reads in the second line of data
y = str2num(tline); %converts to numbers
tline = fgets(fid, 3); %reads in last line of data
N = str2num(tline); %N, also converts to number
fclose(fid); %close file
xx = [x];
yy = [y];
deg = n - 1;
%lagrange
sum=0;
for i=1:length(x)
p=1;
for j=1:length(x)
if j~=i
c = poly(x(j))/(x(i)-x(j));
p = conv(p,c);
end
end
term = p*y(i);
sum= sum + term;
end
%max x value
x_n = max(x);
%plotting the polynomial and data points
xs = linspace(x(1), x_n, N);
ys = p(xs); %this is where I have a mistake when using p
plot(xx,ys, 'r'); %plotting the curve/line
hold on;
plot(x, y, '-o');%plotting the points
0 commentaires
Réponse acceptée
KSSV
le 9 Mar 2021
You can evaluate polyval using:
deg = length(p)-1 ; % degree of he polynomial
% get powers of x till deg
X = xs'.^(deg:-1:0) ;
y = sum(p.*X,2) ; % assuming p has coefficients are in decresing powers of n
9 commentaires
Walter Roberson
le 9 Mar 2021
Using sum as a variable name leads to problems more often than not, as it is very common to want to use sum as a function in the same section of code. We advise to never use sum as the name of a variable.
Plus de réponses (0)
Voir également
Catégories
En savoir plus sur Discrete Data Plots 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!
