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 个)

3 个评论

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.
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!

Translated by