Stan Math Library  2.14.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)),
14  m2_(Eigen::MatrixXd::Zero(n, n)) {
15  restart();
16  }
17 
18  void restart() {
19  num_samples_ = 0;
20  m_.setZero();
21  m2_.setZero();
22  }
23 
24  void add_sample(const Eigen::VectorXd& q) {
25  ++num_samples_;
26 
27  Eigen::VectorXd delta(q - m_);
28  m_ += delta / num_samples_;
29  m2_ += (q - m_) * delta.transpose();
30  }
31 
32  int num_samples() { return num_samples_; }
33 
34  void sample_mean(Eigen::VectorXd& mean) { mean = m_; }
35 
36  void sample_covariance(Eigen::MatrixXd& covar) {
37  if (num_samples_ > 1)
38  covar = m2_ / (num_samples_ - 1.0);
39  }
40 
41  protected:
42  double num_samples_;
43  Eigen::VectorXd m_;
44  Eigen::MatrixXd m2_;
45  };
46 
47  }
48 }
49 #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:23

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