Stan Math Library  2.20.0
reverse mode automatic differentiation
inverse_spd.hpp
Go to the documentation of this file.
1 #ifndef STAN_MATH_PRIM_MAT_FUN_INVERSE_SPD_HPP
2 #define STAN_MATH_PRIM_MAT_FUN_INVERSE_SPD_HPP
3 
8 
9 namespace stan {
10 namespace math {
11 
17 template <typename T>
18 inline Eigen::Matrix<T, Eigen::Dynamic, Eigen::Dynamic> inverse_spd(
19  const Eigen::Matrix<T, Eigen::Dynamic, Eigen::Dynamic>& m) {
20  using Eigen::Dynamic;
21  using Eigen::LDLT;
22  using Eigen::Matrix;
23  check_square("inverse_spd", "m", m);
24  check_symmetric("inverse_spd", "m", m);
25  Matrix<T, Dynamic, Dynamic> mmt = T(0.5) * (m + m.transpose());
26  LDLT<Matrix<T, Dynamic, Dynamic> > ldlt(mmt);
27  if (ldlt.info() != Eigen::Success)
28  domain_error("invese_spd", "LDLT factor failed", "", "");
29  if (!ldlt.isPositive())
30  domain_error("invese_spd", "matrix not positive definite", "", "");
31  Matrix<T, Dynamic, 1> diag_ldlt = ldlt.vectorD();
32  for (int i = 0; i < diag_ldlt.size(); ++i)
33  if (diag_ldlt(i) <= 0)
34  domain_error("invese_spd", "matrix not positive definite", "", "");
35  return ldlt.solve(Eigen::Matrix<T, Eigen::Dynamic, Eigen::Dynamic>::Identity(
36  m.rows(), m.cols()));
37 }
38 
39 } // namespace math
40 } // namespace stan
41 #endif
void check_square(const char *function, const char *name, const matrix_cl &y)
Check if the matrix_cl is square.
void domain_error(const char *function, const char *name, const T &y, const char *msg1, const char *msg2)
Throw a domain error with a consistently formatted message.
Eigen::Matrix< T, Eigen::Dynamic, Eigen::Dynamic > inverse_spd(const Eigen::Matrix< T, Eigen::Dynamic, Eigen::Dynamic > &m)
Returns the inverse of the specified symmetric, pos/neg-definite matrix.
Definition: inverse_spd.hpp:18
void check_symmetric(const char *function, const char *name, const matrix_cl &y)
Check if the matrix_cl is symmetric.

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