Lagrange Interpolation Code Error/Help

조회 수: 9 (최근 30일)
Manny
Manny 2021년 3월 9일
댓글: Manny 2021년 3월 9일
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

채택된 답변

KSSV
KSSV 2021년 3월 9일
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
Walter Roberson
Walter Roberson 2021년 3월 9일
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.
Manny
Manny 2021년 3월 9일
That makes so much sense! I didn't realize sum was already a variable name so now understand why there were so many issues.
Now the only issue left that I can see is that my data points are being plotted on a straight line and not on the curve. I notice the x axis with 10^4 on the top.
I apologize for asking so many questions and I appreciate all of the help!!

댓글을 달려면 로그인하십시오.

추가 답변 (0개)

카테고리

Help CenterFile Exchange에서 Data Converters에 대해 자세히 알아보기

태그

Community Treasure Hunt

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

Start Hunting!

Translated by