User defined functions for standard deviation

2 views (last 30 days)
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 Comment
Walter Roberson
Walter Roberson on 13 Mar 2013
Naming a variable "sum" is going to lead to problems. Same with "mean".

Sign in to comment.

Answers (1)

Azzi Abdelmalek
Azzi Abdelmalek on 13 Mar 2013
Edited: Azzi Abdelmalek on 13 Mar 2013
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

Categories

Find more on MATLAB 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!