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
% 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:
Post a Comment