Really confused why the QR output using RcppArmadillo is different than QR output from R; Armadillo documentation doesnt give a clear answer either. Essentially when I give R a matrix Y that is n * q (say 1000 X 20 ) , I get back Q which is 1000 X 20 and R 20 X 1000. This is what I need. But when I use the QR solver in Armadillo, it throws me back Q 1000 X 1000 and R
1000 X 20. Can I call R’s qr function instead? I need Q to have dimension n x q, not q x q. Code below is what I am using(its a part of a bigger function).
If someone can suggest how to do it in RcppEigen, that’d be helpful too.
library(inline)
library(RcppArmadillo)
src <- '
Rcpp::NumericMatrix Xr(Xs);
int q = Rcpp::as<int>(ys);
int n = Xr.nrow(), k = Xr.ncol();
arma::mat X(Xr.begin(), n, k, false);
arma::mat G, Y, B;
G = arma::randn(n,q);
Y = X*G;
arma::mat Q, R;
arma::qr(Q,R,Y);
return Rcpp::List::create(Rcpp::Named("Q")=Q,Rcpp::Named("R")=R,Rcpp::Named("Y")=Y);'
rsvd <- cxxfunction(signature(Xs="numeric", ys="integer"), body=src, plugin="RcppArmadillo")
(NOTE: This answer explains why R and RcppArmadillo return matrices with different dimensions, but not how to make RcppArmadillo return the 1000*20 matrix that R does. For that, perhaps take a look at the strategy used near the bottom of the
qr.Q()function definition.)R’s
qr()function does not return Q directly. For that, you need to useqr.Q(), like this:Notice that
qr.Q()returns a matrix of the the same dimension asm, rather than a full 5*5 Q matrix. You can use thecomplete=argument to control this behavior, and get a Q matrix of full dimension:In your case, it sounds like RcppArmadillo is returning the full 1000×1000 Q matrix (like
qr.Q(q(m, complete=FALSE))would), rather than just its 1st 20 columns (likeqr.Q(q(m))would).