Evaluating a value of a function and add to the previous value using for loop.
Show older comments
I have the following function; A=(1./pi).*sin(180).*gamma(2).*(((T+x).^-2)+(abs(T-x).^-2).*sign(T-x));
and want to evaluate its value for different value for T and add all the previous evaluated values. The code I' ve written is the following;
a=17.6e-6;
x=0.1.*a;
l=0.1.*a;
sum=0;
for T=x:0.1*a:a
W_z2=(1./pi).*sin(180).*gamma(2).*(((T+x).^-2)+(abs(T-x).^-2).*sign(T-x));
W=W_z2.*l.*l;
sum=sum+W;
end
disp(sum)
The answer it gives is "NaN". Please help me with this.
Thanks
2 Comments
A couple of points to note:
- Don't call a variable 'sum', there is a function of that name
- The sin function takes angles in radians so sin(180) is highly unlikely to be what you want. Either use sind(180) or convert your angles to radians.
To find your NaN, step in and debug!
Richardson Joseph
on 26 Feb 2018
Answers (1)
Jan
on 26 Feb 2018
The result is exactly, what is expected. Why do you assume it is wrong?
The formula contains the term:
abs(T-x) .^ -2
In the first iteration T=x, such that it is:
abs(T - x) .^ -2 =
abs(0) .^ -2 =
1 / 0 ^ 2 =
NaN
It is hard to suggest a modification, because you did not explain, why you start the summation at T=x.
By the way: Do not use "sum" as name of a variable, because it is a built-in function. See this:
clear('sum');
sum(1:10)
sum = 4711
sum(1:10)
Confusing!
Categories
Find more on Loops and Conditional Statements in Help Center and File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!