User defined functions for standard deviation

조회 수: 14 (최근 30일)
Katherine Brideau
Katherine Brideau 2013년 3월 13일
Hi. I'm trying to come up with a function that calculates the standard deviation of an array. I understand there's a built in function that does this but I'm not allowed to use it for my class.
Here's what I have so far,I seem to have hit a wall and would really appreciate any help or suggestions.
Thanks!!! :)
x = [1 2 3 4];
sum = 0;
k = length(x);
for i = 1: k
sum = sum+x(i);
mean = (sum)/k;
stdev = ((x(i)-mean).^2);
stdev = sqrt((stdev)/k);
end
  댓글 수: 1
Walter Roberson
Walter Roberson 2013년 3월 13일
Naming a variable "sum" is going to lead to problems. Same with "mean".

댓글을 달려면 로그인하십시오.

답변 (1개)

Azzi Abdelmalek
Azzi Abdelmalek 2013년 3월 13일
편집: Azzi Abdelmalek 2013년 3월 13일
sum and mean are built-in functions, use instead for example som and moy.
You should use two for loop, the first to calculate the mean of x, and the second to calculate the std of x. Note that the Matlab function std calculate
sqrt(sum((xi-mean(x))^2/(n-1))) % n is the length of x

Community Treasure Hunt

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

Start Hunting!

Translated by