Summation subroutine giving result as NaN (not a number)!

4 次查看(过去 30 天)
In the code below I'm trying to produce the following summation notation with the answers expected being 1,-2,1 (second derivative,central finite difference coefficient)
However when I run my code the answer for S = NaN, and I'm a bit lost as to where I've gone wrong.
n = 2;
k = n/2;
for j=0:n
S = 0;
for i=0:n
if (i~=j)
end
sum=0;
for m=0:n
if (m~=j) && (m~=i)
end
prod=1.0;
for l=0:n
if (l~=j) && (l~=i) && (l~=m)
prod=prod*(n/2-l)/(j-l);
end
end
prod=prod*1/(j-m);
sum=sum+prod;
end
S=S*(1/(j-i))*sum;
end
end
Any help much appreciated, thanks in advance.
  3 个评论
Ive J
Ive J 2021-1-17
Your indices for j and m begin from 0, so you end up with division by zero, so sum is always NaN.
A = NaN;
A + 1
ans =
NaN
btw, as Sargondjani also mentioned, it's always a bad practice to use MATLAB functions as variables (although MATLAB doesn't throw error).

请先登录,再进行评论。

采纳的回答

David Goodmanson
David Goodmanson 2021-1-19
Hi Louis,
the basic problem is that in the product calculation you have
for l=0:n
if (l~=j) && (l~=i) && (l~=m)
prod=prod*(n/2-l)/(j-l);
end
end
which is correct, but in the first sum calculation (similarly for the second) you have
for m=0:n
if (m~=j) && (m~=i)
end
...
end
which does not make use of the 'if' check because the 'if' is immediatly followed by an 'end'. The following code changes that. I also used q instead of l (small L) because it is hard to distinguish l from 1, and did not use sum and prod for variables since they are Matlab functions and the possibility of getting mysterioso results is high. I also found that in this instance for whatever reason it was easier to keep track without using indentation, which can always be added.
n = 6; j = 3;
si = 0;
for i = 0:n
if (i~=j)
sm = 0;
for m=0:n
if (m~=j) && (m~=i)
p = 1;
for q=0:n
if (q~=j) && (q~=i) && (q~=m)
p = p*(n/2-1)/(j-q);
end
end
sm = sm + p/(j-m);
end
end
si = si + sm/(j-i);
end
end
si

更多回答(0 个)

类别

Help CenterFile Exchange 中查找有关 Logical 的更多信息

Community Treasure Hunt

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

Start Hunting!

Translated by