File Exchange

## Cumulative Mean and Variance

version 1.0.0.0 (1.79 KB) by Sumedh Joshi

### Sumedh Joshi (view profile)

Computes cumulative the mean/variance of a vector X along an arbitrary dimension

Updated 26 Feb 2010

>> Y = cummean(X,DIM);
if X is MxN, Y is also MxN. To illustrate the functionality, lets assume X is a 1xN vector. Then, Y is a 1xN vector where the n-th entry in Y is given by mean(X(1:n)). So, Y(end) = mean(X), and Y(1) = X(1). cumvar works in the same way, and this can be done on an arbitrary dimensional X along dimension DIM. See screenshot for an example.

These functions are useful (at least to me) for determining how many iterations of a process are required until the mean and variance of the process are stable (ie: not changing with increasing iterations). Maybe useful to people doing Markhov chain stuff?

### Cite As

Sumedh Joshi (2020). Cumulative Mean and Variance (https://www.mathworks.com/matlabcentral/fileexchange/26791-cumulative-mean-and-variance), MATLAB Central File Exchange. Retrieved .

Sumedh Joshi

### Sumedh Joshi (view profile)

Oleg,

I was not aware of bsxfun when I coded this; you're right that for loops and fevals are an inefficient way to solve this problem.

Thanks for the learning experience,
Sumedh

Oleg Komarov

### Oleg Komarov (view profile)

No H1 line, poorly commented, help can be improved.
Uses eval and loops (really bad) for something that can be achieved as:

% Inputs
dim = 2;
X = rand(100,5);
cumcount = 1:size(X,dim);
if dim == 1
cumcount = cumcount.';
end

cummean = bsxfun(@rdivide, cumsum(X,dim), cumcount);
cumvar = bsxfun(@rdivide, cumsum(X.^2,dim), cumcount) -cummean.^2;

Oleg

##### MATLAB Release Compatibility
Created with R2007b
Compatible with any release
##### Platform Compatibility
Windows macOS Linux