森之张卫东 发表于 2015-9-18 20:58

运行平均数---例题

运行平均数当我们键入一些变量总想得到他的统计量。MATLAB内建函数mean和std就是进行统计数据运算的。我们对一系列的数利用这两个函数进行运算后,再键入一个新数,重新计算。这时我们就可以利用持久内存(persistent memory)提高运算的效率。算术平均数的定义如下:其中xi是N样品中的第i个样品。标准差的定义如下:标准差则体现随机变量取值与其期望值的偏差。标准差的值较大,则表明该随机变量的取值与其期望值的偏差较大,反之,则表明此偏差较小。如果我们能够记录下样本的个数N,样本的和Σxi以及样本的平方和Σx2,我们在任何的时侯就可以通过公式(5.8)和(5.9)计算出它的平均数和标准差。编写一个程序,计算当前输入数据的当前输入数据的平均数和标准差。答案:函数必须能够每接受一次输入值并记录下对应的N,Σxi和Σx2,用于计算当前的平均数和标准差。N,Σxi和Σx2必须存储在持久内存中,这样在两次调用之间,它不会消失。最后函数必须有一种机制,把运行的和清零。



森之张卫东 发表于 2015-9-18 21:00

function = runstats(x)
%RUNSTATS Generate running ave / std deviation
% Function RUNSTATS generates a running average
% and standard deviation of a data set. The
% values x must be passed to this function one
% at a time. A call to RUNSTATS with the argument
% 'reset' will reset tue running sums.
% Define variables:

% ave               --Running average
% msg               --Error message
% n                 --Number of data values
% std               --Running standard deviation
% sum_x             --Running sum of data values
% sum_x2            --Running sum of data values squared
% x                 --Input value
% Record of revisions:
% Date      Programmer      Description of change
% ====      ==========      =====================
% 12/16/98  S. J. Chapman   Original code
% Declare persistent values
persistent n            % Number of input values
persistent sum_x        % Running sum of values
persistent sum_x2       % Running sum of values squared
% Check for a legal number of input arguments.
msg = nargchk(1,1,nargin);
error(msg);

% If the argument is 'reset', reset the running sums.
if x == 'reset'
    n = 0;
    sum_x = 0;
    sum_x2 = 0;
else
    n = n + 1;
    sum_x = sum_x + x;
    sum_x2 = sum_x2 + x^2;
end

% Calculate ave and sd
if n == 0
    ave = 0;
    std = 0;
elseif n == 1
    ave = sum_x;
    std = 0;
else
    ave = sum_x / n;
    std = sqrt((n*sum_x2 - sum_x^2) / (n*(n - 1)));
end

森之张卫东 发表于 2015-9-18 21:00

上传附件,具体内容!
页: [1]
查看完整版本: 运行平均数---例题