Automatic Differentiation
 
Loading...
Searching...
No Matches
generalized_inverse.hpp
Go to the documentation of this file.
1#ifndef STAN_MATH_PRIM_FUN_GENERALIZED_INVERSE_HPP
2#define STAN_MATH_PRIM_FUN_GENERALIZED_INVERSE_HPP
3
9
10namespace stan {
11namespace math {
12
29template <typename EigMat, require_eigen_t<EigMat>* = nullptr,
30 require_not_vt_var<EigMat>* = nullptr>
31inline Eigen::Matrix<value_type_t<EigMat>, EigMat::ColsAtCompileTime,
32 EigMat::RowsAtCompileTime>
33generalized_inverse(const EigMat& G) {
34 const auto& G_ref = to_ref(G);
35 if (G_ref.size() == 0)
36 return {};
37
38 if (G_ref.rows() == G_ref.cols()) {
39 Eigen::CompleteOrthogonalDecomposition<
40 Eigen::Matrix<value_type_t<EigMat>, EigMat::RowsAtCompileTime,
41 EigMat::ColsAtCompileTime>>
42 complete_ortho_decomp_G = G_ref.completeOrthogonalDecomposition();
43 if (!(complete_ortho_decomp_G.rank() < G_ref.rows()))
44 return inverse(G_ref);
45 else
46 return complete_ortho_decomp_G.pseudoInverse();
47 }
48
49 if (G_ref.rows() < G_ref.cols()) {
50 return (G_ref * G_ref.transpose()).ldlt().solve(G_ref).transpose();
51 } else {
52 return (G_ref.transpose() * G_ref).ldlt().solve(G_ref.transpose());
53 }
54}
55
56} // namespace math
57} // namespace stan
58
59#endif
Eigen::Matrix< value_type_t< EigMat >, EigMat::ColsAtCompileTime, EigMat::RowsAtCompileTime > generalized_inverse(const EigMat &G)
Returns the Moore-Penrose generalized inverse of the specified matrix.
ref_type_t< T && > to_ref(T &&a)
This evaluates expensive Eigen expressions.
Definition to_ref.hpp:17
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
The lgamma implementation in stan-math is based on either the reentrant safe lgamma_r implementation ...
Definition fvar.hpp:9