1#ifndef STAN_MATH_PRIM_FUN_GENERALIZED_INVERSE_HPP
2#define STAN_MATH_PRIM_FUN_GENERALIZED_INVERSE_HPP
30template <
typename EigMat, require_eigen_t<EigMat>* =
nullptr,
31 require_not_vt_var<EigMat>* =
nullptr>
32inline Eigen::Matrix<value_type_t<EigMat>, EigMat::ColsAtCompileTime,
33 EigMat::RowsAtCompileTime>
35 const auto& G_ref =
to_ref(G);
36 if (G_ref.size() == 0)
39 if (G_ref.rows() == G_ref.cols()) {
40 Eigen::CompleteOrthogonalDecomposition<
41 Eigen::Matrix<value_type_t<EigMat>, EigMat::RowsAtCompileTime,
42 EigMat::ColsAtCompileTime>>
43 complete_ortho_decomp_G = G_ref.completeOrthogonalDecomposition();
44 if (!(complete_ortho_decomp_G.rank() < G_ref.rows()))
47 return complete_ortho_decomp_G.pseudoInverse();
50 if (G_ref.rows() < G_ref.cols()) {
51 return (G_ref * G_ref.transpose()).ldlt().solve(G_ref).transpose();
53 return (G_ref.transpose() * G_ref).ldlt().solve(G_ref.transpose());
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.
Eigen::Matrix< value_type_t< EigMat >, EigMat::RowsAtCompileTime, EigMat::ColsAtCompileTime > inverse(const EigMat &m)
Forward mode specialization of calculating the inverse of the matrix.
The lgamma implementation in stan-math is based on either the reentrant safe lgamma_r implementation ...