Stan Math Library  2.6.3
probability, sampling & optimization
 All Classes Namespaces Files Functions Variables Typedefs Enumerator Friends Macros
welford_covar_estimator.hpp
Go to the documentation of this file.
1 #ifndef STAN_MATH_PRIM_MAT_FUN_WELFORD_COVAR_ESTIMATOR_HPP
2 #define STAN_MATH_PRIM_MAT_FUN_WELFORD_COVAR_ESTIMATOR_HPP
3 
5 #include <vector>
6 
7 namespace stan {
8 
9  namespace math {
10 
12  public:
13  explicit welford_covar_estimator(int n)
14  : _m(Eigen::VectorXd::Zero(n)),
15  _m2(Eigen::MatrixXd::Zero(n, n)) {
16  restart();
17  }
18 
19  void restart() {
20  _num_samples = 0;
21  _m.setZero();
22  _m2.setZero();
23  }
24 
25  void add_sample(const Eigen::VectorXd& q) {
26  ++_num_samples;
27 
28  Eigen::VectorXd delta(q - _m);
29  _m += delta / _num_samples;
30  _m2 += (q - _m) * delta.transpose();
31  }
32 
33  int num_samples() { return _num_samples; }
34 
35  void sample_mean(Eigen::VectorXd& mean) { mean = _m; }
36 
37  void sample_covariance(Eigen::MatrixXd& covar) {
38  if (_num_samples > 1)
39  covar = _m2 / (_num_samples - 1.0);
40  }
41 
42  protected:
43  double _num_samples;
44 
45  Eigen::VectorXd _m;
46  Eigen::MatrixXd _m2;
47  };
48 
49  } // prob
50 
51 } // stan
52 
53 
54 #endif
void add_sample(const Eigen::VectorXd &q)
void sample_covariance(Eigen::MatrixXd &covar)
boost::math::tools::promote_args< T >::type mean(const std::vector< T > &v)
Returns the sample mean (i.e., average) of the coefficients in the specified standard vector...
Definition: mean.hpp:23

     [ Stan Home Page ] © 2011–2015, Stan Development Team.