polynomial interpolation with lagrange form!!!

I implemented a function of lagrange form and i want to use it to interpolate the function f(x) = sin(4x) for some datapoints!! i wrote the script for that but it always gives me error !!! can anyone help me with that !!!
this is my code
xval = 0:10;
pval = xval.^2;
xx = linspace(0,10);
yy = lagrange1(xx,xval,pval);
plot(xval,pval,'o',xx,yy,'.')

4 件のコメント

Torsten
Torsten 2022 年 1 月 25 日
Since we don't see lagrange1, we can't reproduce the error.
Anas Gharsa
Anas Gharsa 2022 年 1 月 25 日
this is my lagrange1
function [Pval,Lval] = lagrange1(x,xval,f)
n = length(x); ntab=length(xval);
if nargout ==2 % in this case also the tabulation of the basis Lagrange polynomials is desired
Lval=ones(n,ntab);
for i=1:n
for j=[1:i-1,i+1:n]
Lval(i,:) = Lval(i,:).*(xval-x(j))/(x(i)-x(j));
end
end
f = f(:);
Pval = Lval'*f;
Pval=Pval'; % row vector in output
else % in this case only the tabulation of the interpolating polynomial is desired
Pval = zeros(1,ntab);
for i=1:n
Lval = ones(1,ntab);
for j=[1:i-1,i+1:n]
Lval = Lval.*(xval-x(j))/(x(i)-x(j));
end
Pval = Pval + Lval*f(i);
end
end
end
Torsten
Torsten 2022 年 1 月 25 日
And the error message ?
Anas Gharsa
Anas Gharsa 2022 年 1 月 25 日

サインインしてコメントする。

 採用された回答

Alagu Sankar Esakkiappan
Alagu Sankar Esakkiappan 2022 年 1 月 28 日
編集済み: Alagu Sankar Esakkiappan 2022 年 1 月 28 日

0 投票

Hello!
I see that you're trying to interpolate a polynomial but running into errors. I checked your code along with your function lagrange1 from your comments. It seems that you are running into an indexing error in the function lagrange1 on the line "Pval = Pval + Lval*f(i)". From what I observed using Breakpoint, you are trying to access f(12) when infact f only contains 11 elements to begin with.
Here are the Workspace values before the exact occurence of error:
If you try to evaluate the expression "Pval = Pval + Lval*f(i)" at this point ( based on values from above image ), you access f(12), thereby running into the error. I suggest for easier debugging, Try creating a Breakpoint on the line where error is caused in MATLAB. It'll give a more comprehensive view of the Codeflow and to narrow down exact occurence of error.

1 件のコメント

Anas Gharsa
Anas Gharsa 2022 年 1 月 28 日
okay i will try that!! thank you so for the reply

サインインしてコメントする。

その他の回答 (0 件)

カテゴリ

ヘルプ センター および File ExchangeInterpolation についてさらに検索

製品

リリース

R2021b

Community Treasure Hunt

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

Start Hunting!

Translated by