- You should user separate variables for looping
- Indexing in MATLAB starts from 1.So, change loop start index to 1
- Inside for loop, the calculation of indices on I,O is being done by using (i-n) and (i+N), but in your code n,N are not defined anywhere and also to sum the values in array use the "sum" function instead of "sigma"
How to find position of a variable element in a variable -input- vector?
2 ビュー (過去 30 日間)
古いコメントを表示
Hello.
So I want to code a Lagrange Interpolation and I got so far:
A = inputdlg({'x','F(x)'},'Data');
I = str2num(A{1,:});
O = str2num(A{2,:});
t = length(I);
g = length(O);
if g == t;
for variable = I,O
for i = 0:g
l(i) = (('x' - I(i-n))*('x' - I(i+N)))/((O(i) - O(i-n))*(O(i) - O(i+N)));
P(i) = O(i)*l(i);
Lagrange = sigma(P);
end
end
else
A = inputdlg({'x','F(x)'},'Data -With equel in/out-');
end
Im stuck on line 8 where each pair of variables have a different value of n&N. I have to define them based on the position of each I or O and repeat products based on them too.
0 件のコメント
回答 (1 件)
Anjaneyulu Bairi
2024 年 12 月 3 日
Hi,
Your code snippet has a few issues that can cause errors around 8th line.
Refer the below code for correct Implementation:
% Prompt for input
A = inputdlg({'x', 'F(x)'}, 'Data');
I = str2num(A{1}); % x values
O = str2num(A{2}); % F(x) values
% Initialize variables
n = length(I);
Lagrange = 0; % Initialize the Lagrange polynomial
% Define symbolic variable x for interpolation
syms x;
% Compute the Lagrange polynomial
for i = 1:n
% Initialize the i-th Lagrange basis polynomial
l_i = 1;
for j = 1:n
if j ~= i
% Compute the product for the basis polynomial
l_i = l_i * ((x - I(j)) / (I(i) - I(j)));
end
end
% Accumulate the Lagrange polynomial
Lagrange = Lagrange + O(i) * l_i;
end
% Display the resulting polynomial
disp('The Lagrange Interpolating Polynomial is:');
disp(Lagrange);
Hope this helps!
0 件のコメント
参考
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!