How to find position of a variable element in a variable -input- vector?

36 Ansichten (letzte 30 Tage)
Ali
Ali am 2 Dez. 2024 um 16:48
Beantwortet: Anjaneyulu Bairi vor etwa 19 Stunden
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.

Antworten (1)

Anjaneyulu Bairi
Anjaneyulu Bairi vor etwa 19 Stunden
Hi,
Your code snippet has a few issues that can cause errors around 8th line.
  • 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"
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!

Kategorien

Mehr zu Interpolation finden Sie in Help Center und File Exchange

Community Treasure Hunt

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

Start Hunting!

Translated by