Finding the standard deviation of a matrix
105 vues (au cours des 30 derniers jours)
Afficher commentaires plus anciens
I'm trying to find the standard deviation of a matrix, but I'm getting a different answer when I do it myself than what matlab gives me.
I know that to find the standard deviation you:
1.Take the mean of all the #s
2.Then for each of those #s you subtract the mean and then square it
3.Then find the mean for all those new #s and then take the square root of that #
Heres what I have for the code:
a=[3 -2 1;4 0 5;1 2.2 -3]
m=numel(a)
sum=0;
for i=1:m;
sum=sum+a(i);
avg=sum/m;
end
avg
o=length(a)
sd=0;
for i=1:o;
sd=sd+(a(i)-avg)^2;
sd=(sd/(o-1))^1/2;
end
sd
I got 2.49 for the standard deviation but matlab is giving me 0.5377. I have to use loops to do this I can't just use matlab commands for standard deviation. Any insight as to what I might be doing wrong is appreciated. Thank you.
0 commentaires
Réponses (2)
John D'Errico
le 14 Avr 2016
Modifié(e) : John D'Errico
le 14 Avr 2016
You are getting a different answer because you are not even doing what you said you wanted to do. Should you be surprised? Your code does some nasty stuff inside that loop that does not do what you apparently think you wanted to do.
By the way, a REALLY bad idea is to use the letter o for a variable name. One day you will end up with bugs in your code because you typed the number 0 instead of o someplace.
Anyway, there are two possible standard deviations to consider. A population standard deviation, or a sample standard deviation. The difference depends on whether you divide by n or n-1. What you described, taking a mean, implies a population standard deviation. But then you divided by o-1.
std(a(:))
does what you want, unless you really did want a population standard deviation. In that case, use
std(a(:),1)
Do you really feel the need to verify that MATLAB knows how to compute a standard deviation, so that you need to do it by hand to check?
std(a(:))
ans =
2.64344051905425
sqrt(sum((a(:) - mean(a(:))).^2)/(numel(a)-1))
ans =
2.64344051905425
Yes. You could do it using loops. But if you intend to learn MATLAB, then learn to use it as it should be used.
0 commentaires
Azzi Abdelmalek
le 14 Avr 2016
Modifié(e) : Azzi Abdelmalek
le 14 Avr 2016
you can use std function
std(a(:))
If you want to use your for loop, you have to correct some errors
a=[3 -2 1;4 0 5;1 2.2 -3]
m=numel(a)
som=0;
for i=1:m;
som=som+a(i);
end
avg=som/m;
o=numel(a)
sd=0;
for i=1:o;
sd=sd+(a(i)-avg)^2;
end
sd=(sd/(o-1))^(1/2)
0 commentaires
Voir également
Catégories
En savoir plus sur Loops and Conditional Statements dans Help Center et File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!