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
10
11namespace stan {
12namespace math {
13
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>
34generalized_inverse(const EigMat& G) {
35 const auto& G_ref = to_ref(G);
36 if (G_ref.size() == 0)
37 return {};
38
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()))
45 return inverse(G_ref);
46 else
47 return complete_ortho_decomp_G.pseudoInverse();
48 }
49
50 if (G_ref.rows() < G_ref.cols()) {
51 return (G_ref * G_ref.transpose()).ldlt().solve(G_ref).transpose();
52 } else {
53 return (G_ref.transpose() * G_ref).ldlt().solve(G_ref.transpose());
54 }
55}
56
57} // namespace math
58} // namespace stan
59
60#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:28
The lgamma implementation in stan-math is based on either the reentrant safe lgamma_r implementation ...