2
votes

I am trying to calculate the standard deviation in MATLAB using the formula

for i=1:n 
s=sqrt(sum((h(i)-mean(h))^2)/(n-1));
end

where n is the number of rows in a single column vector, but the result is different as calculated by std(h). In my project I can not use std function

Please help me.

2

2 Answers

5
votes

In my opinion you would be better off not using a for loop and use vectorized code instead.

s1 = sqrt(sum((h - mean(h)).^2)./(n-1))

Here sum takes care of the summation accomplished by the for loop.

If you do want to use a for-loop, you want to add each individual term inside the loop and then take the square root of that; i.e. do not use sum inside the loop:

clc
clear

h = rand(1,100);
M = mean(h);

n = length(h);

s0 = 0; %// Initialize s0, the standard deviation you wish to calculate.
for i=1:n     
    s0 = s0 + (h(i)- M)^2; %// add each calculated s0 to its previous value. That's the sum.
end

s0 = sqrt(s0/(n-1))

%// Calculate values using vectorized code of Matlab std function.
s1 = sqrt(sum((h - mean(h)).^2)./(n-1))
s2 = std(h)

Checking s0, s1 and s2:

s0 =

    0.2842


s1 =

    0.2842


s2 =

    0.2842
0
votes

I don't know Matlab, but the only loop should be for the summation of all the (data - average)^2.
There is no looping with the /(n-1) or sqrt().

Right it looks like you have something like s.d. =

enter image description here

But you want it to match

enter image description here

So perform the /(n-1) and square root operations on the variable found by that summation.