error in matlab code for mean and standard deviation

6 views (last 30 days)
Hello all,
I have written following matlab code for calculating the mean and standard deviation of x but I am getting an error for mean and standard deviation as NaN (Not a number). Kindly help. What is wrong with my code.
clc;
close all;
clear all;
x = [4.2426 + 3.1659i
2.2956 + 2.3891i
-2.2271 + 4.5607i
-1.9326 - 3.1940i
3.6840 + 3.0343i
0.0677 + 2.9262i
-2.9779 - 1.4531i
-2.4633 + 3.2697i
-3.9887 + 0.4685i
-2.9322 - 2.2252i
-4.3754 - 2.6187i
-3.4865 - 3.4461i];
sum_x = 0;
sum_x2 = 0;
n=0;
while x>=0
n=n+1;
sum_x=sum_x+x;
sum_x2=sum_x2+x^2;
end
x_bar=sum_x/n;
std_dev=sqrt((n*sum_x2-sum_x^2)/(n*(n-1)));

Accepted Answer

Walter Roberson
Walter Roberson on 22 Apr 2014
You do not change "x" inside your loop
while x>=0
so if the loop were to get entered at all, it would run forever. We can therefore deduce that
x>=0
is not considered "true" when it is encountered. You initialized n=0 and you do not change it (because the "if" is not true), so your n is still 0 when you divide by n in the next line and the line after that.
Your x is a vector of complex values. What meaning do you associate with a vector of values being collectively >= 0? What meaning would you associate with any given complex value stored in x being >= 0 ?
A >= B returns a logical array with elements set to logical 1 (true) where A is greater than or equal to B; otherwise, it returns logical 0 (false). The test compares only the real part of numeric arrays
so >=0 would ignore the imaginary part, confusing the reader at the very least. Your first two real values in the vector are >=0 but the third value is not, so your >=0 test is going to result in a mix of true and false vector elements.
An evaluated expression is true when the result is nonempty and contains all nonzero elements (logical or real numeric). Otherwise, the expression is false
Some of the results of the >=0 were false which is 0, so the bit about "all nonzero elements" does not hold, leading to the "Otherwise, the expression is false". So when you compare the vector x>=0 then you are going to get a false on the comparison, leading to n being 0 as described above.
If you were to loop through the elements in x one by one, testing each in sequence, then the first negative real part would end the loop. It is not at all clear why you would wish to consider negative values to not be valid for the purpose of calculating mean and standard deviation.
It would help if you were to document your reason for having a "while" loop at that point in your code.

More Answers (0)

Categories

Find more on Creating and Concatenating Matrices 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!