Please explain for me this code , and what does each function do in detail ?
显示 更早的评论
function s=lagrangeP(x,X,Y)
format long
n=size(X);
L=ones(n);
for i=1:n
for j=1:n
if (i~=j)
L(i)=L(i).*(x-X(j))./(X(i)-X(j));
end
end
end
s=0;
for i=1:n
s=s+Y(i)*L(i);
end
回答(1 个)
Kevin Holly
2021-10-13
1 个投票
This was answered here:
3 个评论
Kevin Holly
2021-10-13
编辑:Kevin Holly
2021-10-13
Here is a more detail explanation.
function s=lagrangeP(x,X,Y) %This creates the function lagrangeP. s is the output. x, X, and Y are the inputs.
format long %This allows the display of numbers in the command window to appear long (many decimal places)
%This section preallocates the variable L before it goes through the for loop. This reduces computation time, so you don't an array changing sizes
%after every loop. Now, you will just be replacing values in an array of a set size.
n=size(X);%This finds the size of X and saves the dimensions as a vector array with the variable name n.
L=ones(n);%This creates a n by n matrix of ones equal to the dimensions of X.
%This section calculates values within the matrix L
for i=1:n %This creates a for loop by giving values for i that starts with 1 and then increases by 1 until it reaches an element size of n
for j=1:n %This does the same think but for variable j
if (i~=j) %This if condition states that the line below only applies when the value of i does not equal the value of j
L(i)=L(i).*(x-X(j))./(X(i)-X(j));%These calculations can be found in the equation below. L(i) goes through each element of the matrix L when in the for loop from L(1) to L(n).
end
end
end
s=0;
for i=1:n
s=s+Y(i)*L(i);
end

You can find more details about the equation in the following:
The above link was provided in a comment by Walter in the previously linked MATLAB Answers post.
Alhussain AlAbbas
2021-10-14
Kevin Holly
2021-10-14
No problem. If this answers your question, I would appreciate it if you accepted the answer.
类别
在 帮助中心 和 File Exchange 中查找有关 Logical 的更多信息
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!