使用MATLAB的标准偏差

时间:2015-01-06 13:46:42

标签: matlab

我正在尝试使用公式

计算 MATLAB 中的标准差
for i=1:n 
s=sqrt(sum((h(i)-mean(h))^2)/(n-1));
end

其中n是单个列向量中的行数,但结果与std(h)计算的结果不同。在我的项目中,我无法使用std function

请帮帮我。

2 个答案:

答案 0 :(得分:4)

在我看来,最好不要使用for循环,而是使用矢量化代码。

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

这里sum负责for循环完成的总和。

如果你想使用for循环,你想在循环中添加每个单独的术语,然后取平方根;即不要在循环中使用sum

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)

检查s0,s1和s2:

s0 =

    0.2842


s1 =

    0.2842


s2 =

    0.2842

答案 1 :(得分:0)

我不了解Matlab,但唯一的循环应该是所有(数据 - 平均)^ 2的总和。
/(n-1)或sqrt()没有循环。

看起来你有像s.d这样的东西。 =

enter image description here

但你希望它匹配

enter image description here

因此对该求和找到的变量执行/(n-1)和平方根运算。