r - Create a list of RcppArmadillo matrices -


deep inside mcmc algorithm need multiply user-provided list of matrices vector, i.e., following piece of rcpp , rcpparmadillo code called multiple times per mcmc iteration:

list mat_vec1 (const list& mats, const vec& y) {     int n_list = mats.size();     rcpp::list out(n_list);     (int = 0; < n_list; ++i) {         out[i] = as<mat>(mats[i]) * y;     }     return(out); } 

the user-provided list mats remains fixed during mcmc, vector y changes in each iteration. efficiency paramount , i'm trying see if can speed code not having convert elements of mats arma::mat many times (it needs done once). tried following approach

list arma_mats (const list& mats) {     int n_list = mats.size();     rcpp::list res(n_list);     (int = 0; < n_list; ++i) {         res[i] = as<mat>(mats[i]);     }     return(res); } 

and then

list mat_vec2 (const list& mats, const vec& y) {     int n_list = mats.size();     rcpp::list amats = arma_mats(mats);     rcpp::list out(n_list);     (int = 0; < n_list; ++i) {         out[i] = amats[i] * y;     }     return(out); } 

but not seem work. pointers of alternative/better solutions welcome.

ok, wrote answer in comment occurred me provide working example in stub created rcpparmadillo.package.skeleton():

// [[rcpp::export]] rcpp::list rcpparma_bothproducts(const arma::colvec & x) {     arma::mat op = x * x.t();     double    ip = arma::as_scalar(x.t() * x);     return rcpp::list::create(rcpp::named("outer")=op,                               rcpp::named("inner")=ip); } 

this returns list outer product (a matrix) , inner product (a scalar) of given vector.

as fast , not: recommend not conjecture rather profile , measure as can. inclination more (standalone) c++ code in armadillo , return @ end minimizing conversions.


Comments