Matlab的加权方差

时间:2019-08-20 08:36:18

标签: matlab standard-deviation variance weighted-average

我研究了如何计算样本的加权标准差或方差,发现这篇非常有帮助的帖子参考了Gatz和Smith的论文,提出了几种方法:https://math.stackexchange.com/questions/823125/sampling-error-with-weighted-mean

现在,我正在尝试了解Matlab在使用“ std(A,w)”时如何计算加权方差。我使用“ edit var”浏览了Matlab帮助和原始代码,但未能理解如何计算加权方差的语法。有人可以为我写下等式还是用几句话描述下面代码的关键行? (在Matlab中键入“ edit var”时,您会找到该函数的完整代码)。

% Weighted variance

其他

if ~isvector(w) || ~isreal(w) || ~isfloat(w) || ...
   (omitnan && ~all(w(~isnan(w)) >= 0)) || (~omitnan && ~all(w >= 0))
    error(message('MATLAB:var:invalidWgts'));
end

if numel(w) ~= n
    if isscalar(w)
        error(message('MATLAB:var:invalidWgts'));
    else
        error(message('MATLAB:var:invalidSizeWgts'));
    end
end

if ~omitnan

    % Normalize W, and embed it in the right number of dims.  Then
    % replicate it out along the non-working dims to match X's size.
    wresize = ones(1,max(ndims(x),dim)); wresize(dim) = n;
    w = reshape(w ./ sum(w), wresize);
    y = sum(w .* abs(x  - sum(w .* x, dim)).^2, dim); % abs guarantees a real result

else
    % Repeat vector W, such that new W has the same size as X
    sz = size(x); sz(end+1:dim) = 1;
    wresize = ones(size(sz)); wresize(dim) = sz(dim);
    wtile = sz; wtile(dim) = 1;
    w = repmat(reshape(w, wresize), wtile);

    % Count up non-NaN weights at non-NaN elements
    w(isnan(x)) = NaN;
    denom = sum(w, dim, 'omitnan'); % contains no NaN, since w >= 0

    x = x - (sum(w .* x, dim, 'omitnan') ./ denom);
    wx2 = w .* abs(x).^2;
    y = sum(wx2, dim, 'omitnan') ./ denom; % abs guarantees a real result

    % Don't omit NaNs caused by computation (not missing data)
    ind = any(isnan(wx2) & ~isnan(w), dim);
    y(ind) = NaN;

0 个答案:

没有答案