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