Important Disclaimer

The purpose of this blog is purely to serve as a compilation of good technical material for my students. No financial or other motives are involved. Most of the content in this blog has been reproduced from other sources. I have made every attempt to mention the source link at the beginning of each blog. All readers are requested to kindly acknowledge that source and not this blog, in case you find the post helpful. However, I have not been able to trace the source links for some of my older posts. I wish to emphasize that this is not intentional and any help in this regard would be appreciated.

Jun 29, 2013

Online computation of mean and variance- Matlab

Finding the mean and std. deviation online is important when it is not possible to store the entire set of values in the memory (say in case of microcontrollers) or when dealing with an incoming stream of values. Below is a code in Matlab for online computation of mean and std. deviation. I have written this based on the algo. given in wikipedia. The logic used in this Matlab code can be used to write code for your microcontroller program. The code:

% online computation of mean and variance
% By Binoy
% for this, you need to know only x(n-1) and x(n) values
% every time a new value comes in, mean and variance are computed
clear all;
clc
prompt = 'What is the number of samples? ';
samples = input(prompt)

prompt_1 = 'input the first sample ';
x_1 = input(prompt_1)

mean_x=x_1;
S_x=0;
for n=2:samples
    prompt_2 = 'input the sample ';
    x = input(prompt_2)
   
    mean_x_n_minus_1= mean_x;
    mean_x= mean_x+((x-mean_x_n_minus_1)/n) % the mean
    S_x= S_x+((x-mean_x_n_minus_1)*(x-mean_x));
    var_x=S_x/(n-1)% the variance
   
   
    end


No comments: