Stan Math Library  2.20.0
reverse mode automatic differentiation
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 namespace math {
9 
11  public:
12  explicit welford_covar_estimator(int n)
13  : m_(Eigen::VectorXd::Zero(n)), m2_(Eigen::MatrixXd::Zero(n, n)) {
14  restart();
15  }
16 
17  void restart() {
18  num_samples_ = 0;
19  m_.setZero();
20  m2_.setZero();
21  }
22 
23  void add_sample(const Eigen::VectorXd& q) {
24  ++num_samples_;
25 
26  Eigen::VectorXd delta(q - m_);
27  m_ += delta / num_samples_;
28  m2_ += (q - m_) * delta.transpose();
29  }
30 
31  int num_samples() { return num_samples_; }
32 
33  void sample_mean(Eigen::VectorXd& mean) { mean = m_; }
34 
35  void sample_covariance(Eigen::MatrixXd& covar) {
36  if (num_samples_ > 1)
37  covar = m2_ / (num_samples_ - 1.0);
38  }
39 
40  protected:
41  double num_samples_;
42  Eigen::VectorXd m_;
43  Eigen::MatrixXd m2_;
44 };
45 
46 } // namespace math
47 } // namespace stan
48 #endif
(Expert) Numerical traits for algorithmic differentiation variables.
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:21

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