1#ifndef STAN_MATH_PRIM_FUN_GENERALIZED_INVERSE_HPP
2#define STAN_MATH_PRIM_FUN_GENERALIZED_INVERSE_HPP
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>
34 const auto& G_ref =
to_ref(G);
35 if (G_ref.size() == 0)
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()))
46 return complete_ortho_decomp_G.pseudoInverse();
49 if (G_ref.rows() < G_ref.cols()) {
50 return (G_ref * G_ref.transpose()).ldlt().solve(G_ref).transpose();
52 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 ...