program for lagranges interpolation method using single for loop

how to program for lagranges interpolation method using single for loop

4 件のコメント

Geoff Hayes
Geoff Hayes 2018 年 8 月 23 日
PJS - what have you tried so far? Please describe what you have attempted and discuss any errors or bugs that you are observing with your code. Right now, your question (or request) is much too vague...
PJS KUMAR
PJS KUMAR 2018 年 8 月 23 日
編集済み: Geoff Hayes 2018 年 8 月 23 日
function sum=Lagrange(x,y,a)
sum = 0;
format shortG
for i = 1:length(x)
u = 1;
l = 1;
for j = 1:length(x)
if j ~= i
u = u * (a - x(j));
l = l * (x(i) - x(j));
end
end
sum= sum + u / l * y(i);
end
Geoff Hayes
Geoff Hayes 2018 年 8 月 23 日
Please rename your local variable sum since it conflicts with the MATLAB built-in function of the same name.
Out of curiosity, why do you want to eliminate the inner for loop? For performance reasons?
PJS KUMAR
PJS KUMAR 2018 年 8 月 23 日
yes, for performance reasons can we write the program by using vector operations.

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

回答 (1 件)

Geoff Hayes
Geoff Hayes 2018 年 8 月 23 日

0 投票

PJS - if we assume that x is a vector/array then u is simply
u = (a - x(1)) * (a - x(2)) * ... * (a - x(i-1)) * (a - x(i+1)) * ... * (a - x(n));
where n is the number of elements in x. If this is true, then couldn't we do something like
for i = 1:length(x)
u = 1;
l = 1;
xt = x;
xt(i) = []; % remove the ith element
u = prod(a - xt);
% etc.
end
We use prod to calculate the product of all elements in the array. Similarly, for l
l = (x(i) - x(1)) * (x(i) - x(2)) * ... * (x(i) - x(i-1)) * (x(i) - x(i+1)) * ... * (ax(i) - x(n));
which means that the above can be replaced with
l = prod(x(i) - xt));
Try the above and see what happens!

カテゴリ

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

質問済み:

2018 年 8 月 23 日

回答済み:

2018 年 8 月 23 日

Community Treasure Hunt

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

Start Hunting!

Translated by