MATLAB Answers

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

44 views (last 30 days)
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 Comments

Sargondjani
Sargondjani on 17 Jan 2021
I would recommend to check all your intermediate results. YOu could for example add lines like:
if isnan(prod)
error('variable prod is NaN')
end
Also note that 'sum' and 'prod' are functions, so you shouldnt use them as a variable names.
Ive J
Ive J on 17 Jan 2021
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).

Sign in to comment.

Accepted Answer

David Goodmanson
David Goodmanson on 19 Jan 2021
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

More Answers (0)

Community Treasure Hunt

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

Start Hunting!

Translated by