image thumbnail
from cumulative statistic with NaN's by Mauro
cumstat calculate the mean and std of an array with NaN's from 1 to n

nancumstat(x,dim)
function [mx, sx] = nancumstat(x,dim)

% [mx, sx] = nancumstat(x,dim)
% 
% [mx, sx] = nancumstat(x) calculate the mean and std of an array as seen below:
%   mx(n,:) = mean(1:n,:)
%   sx(n,:) = std(1:n,:)
%
% dim = 1 --> row wise
% dim = 2 --> col wise
% Missing values (NaN) stay's as NaN's
%
% data arrays without NaN's please use cumstat for speed!

if nargin <2, dim = 1;end
mx = NaN(size(x));
sx = NaN(size(x));

switch dim
    case 1
        for i=1:size(x,2)
            log_nan = ~isnan(x(:,i));
            temp = x(log_nan,i);
            x1 = (1:length(temp))';
            x2 = cumsum(temp-mean(temp));
            x3 = cumsum((temp-mean(temp)).^2);
            mx(log_nan,i) = x2./x1+mean(temp);
            sx(log_nan,i) = sqrt((x1.*x3-x2.^2)./(x1.*(x1-1)));
            clear temp x1 x2 x3
        end
    case 2
        for i=1:size(x,2)
            log_nan = ~isnan(x(i,:));
            temp = x(i,log_nan);
            x1 = (1:length(temp));
            x2 = cumsum(temp-mean(temp),2);
            x3 = cumsum((temp-mean(temp)).^2,2);
            mx(i,log_nan) = x2./x1+mean(temp);
            sx(i,log_nan) = sqrt((x1.*x3-x2.^2)./(x1.*(x1-1)));
            clear temp x1 x2 x3
        end
    otherwise
end

Contact us at files@mathworks.com