1 #ifndef STAN_MATH_PRIM_FUN_QR_Q_HPP
2 #define STAN_MATH_PRIM_FUN_QR_Q_HPP
3
4 #include <stan/math/prim/meta.hpp>
5 #include <stan/math/prim/err.hpp>
6 #include <stan/math/prim/fun/Eigen.hpp>
7 #include <algorithm>
8
9 namespace stan {
10 namespace math {
11
12 /**
13 * Returns the orthogonal factor of the fat QR decomposition
14 *
15 * @tparam EigMat type of the matrix
16 * @param m Matrix.
17 * @return Orthogonal matrix with maximal columns
18 */
19 template <typename EigMat, require_eigen_t<EigMat>* = nullptr>
qr_Q(const EigMat & m)20 Eigen::Matrix<value_type_t<EigMat>, Eigen::Dynamic, Eigen::Dynamic> qr_Q(
21 const EigMat& m) {
22 using matrix_t
23 = Eigen::Matrix<value_type_t<EigMat>, Eigen::Dynamic, Eigen::Dynamic>;
24 check_nonzero_size("qr_Q", "m", m);
25 Eigen::HouseholderQR<matrix_t> qr(m.rows(), m.cols());
26 qr.compute(m);
27 matrix_t Q = qr.householderQ();
28 const int min_size = std::min(m.rows(), m.cols());
29 for (int i = 0; i < min_size; i++) {
30 if (qr.matrixQR().coeff(i, i) < 0) {
31 Q.col(i) *= -1.0;
32 }
33 }
34 return Q;
35 }
36
37 } // namespace math
38 } // namespace stan
39
40 #endif
41