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
12
13namespace stan {
14namespace math {
15
26template <typename EigMat, require_eigen_vt<is_fvar, EigMat>* = nullptr>
27inline Eigen::Matrix<value_type_t<EigMat>, EigMat::RowsAtCompileTime,
28 EigMat::ColsAtCompileTime>
29inverse(const EigMat& m) {
30 using T = typename value_type_t<EigMat>::Scalar;
31 constexpr int R = EigMat::RowsAtCompileTime;
32 constexpr int C = EigMat::ColsAtCompileTime;
33
34 check_square("inverse", "m", m);
35 if (m.size() == 0) {
36 return {};
37 }
38
39 Eigen::Matrix<T, R, C> m_deriv(m.rows(), m.cols());
40 Eigen::Matrix<T, R, C> m_inv(m.rows(), m.cols());
41
42 const Eigen::Ref<const plain_type_t<EigMat>>& m_ref = m;
43 for (size_type j = 0; j < m.cols(); j++) {
44 for (size_type i = 0; i < m.rows(); i++) {
45 m_inv.coeffRef(i, j) = m_ref.coeff(i, j).val_;
46 m_deriv.coeffRef(i, j) = m_ref.coeff(i, j).d_;
47 }
48 }
49
50 m_inv = inverse(m_inv);
51 m_deriv = -multiply(multiply(m_inv, m_deriv), m_inv);
52
53 return to_fvar(m_inv, m_deriv);
54}
55
56} // namespace math
57} // namespace stan
58#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:18
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:29
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 ...