Automatic Differentiation
 
Loading...
Searching...
No Matches
inverse.hpp
Go to the documentation of this file.
1#ifndef STAN_MATH_FWD_FUN_INVERSE_HPP
2#define STAN_MATH_FWD_FUN_INVERSE_HPP
3
11
12namespace stan {
13namespace math {
14
25template <typename EigMat, require_eigen_vt<is_fvar, EigMat>* = nullptr>
26inline Eigen::Matrix<value_type_t<EigMat>, EigMat::RowsAtCompileTime,
27 EigMat::ColsAtCompileTime>
28inverse(const EigMat& m) {
29 using T = typename value_type_t<EigMat>::Scalar;
30 constexpr int R = EigMat::RowsAtCompileTime;
31 constexpr int C = EigMat::ColsAtCompileTime;
32
33 check_square("inverse", "m", m);
34 if (m.size() == 0) {
35 return {};
36 }
37
38 Eigen::Matrix<T, R, C> m_deriv(m.rows(), m.cols());
39 Eigen::Matrix<T, R, C> m_inv(m.rows(), m.cols());
40
41 const Eigen::Ref<const plain_type_t<EigMat>>& m_ref = m;
42 for (size_type j = 0; j < m.cols(); j++) {
43 for (size_type i = 0; i < m.rows(); i++) {
44 m_inv.coeffRef(i, j) = m_ref.coeff(i, j).val_;
45 m_deriv.coeffRef(i, j) = m_ref.coeff(i, j).d_;
46 }
47 }
48
49 m_inv = inverse(m_inv);
50 m_deriv = -multiply(multiply(m_inv, m_deriv), m_inv);
51
52 return to_fvar(m_inv, m_deriv);
53}
54
55} // namespace math
56} // namespace stan
57#endif
typename value_type< T >::type value_type_t
Helper function for accessing underlying type.
void check_square(const char *function, const char *name, const T_y &y)
Check if the specified matrix is square.
auto multiply(const Mat1 &m1, const Mat2 &m2)
Return the product of the specified matrices.
Definition multiply.hpp:19
Eigen::Matrix< value_type_t< EigMat >, EigMat::RowsAtCompileTime, EigMat::ColsAtCompileTime > inverse(const EigMat &m)
Forward mode specialization of calculating the inverse of the matrix.
Definition inverse.hpp:28
Eigen::Matrix< double, Eigen::Dynamic, Eigen::Dynamic >::Index size_type
Type for sizes and indexes in an Eigen matrix with double elements.
Definition typedefs.hpp:11
fvar< T > to_fvar(const T &x)
Definition to_fvar.hpp:15
The lgamma implementation in stan-math is based on either the reentrant safe lgamma_r implementation ...