Skip to content
Prev 5533 / 10988 Next

[Rcpp-devel] fill a NumericMatrix row by row

Thanks for the reply and great libraries Conrad and Romain.

Conrad, my example is a bit too simple maybe, I am really doing:

for i from 1 to m:
   do computation
   store a row of results into a tall m x n matrix

...where i am pretty sure that the time required for computation is more
than storing the results.

Out of curiosity, I tried to do some profiling for row filling of tall
Armadillo matrices vs. column filling. Row filling becomes worse when the
rows are long.  I guess the memory allocation could obscure some speed
differences:

library(Rcpp)
library(inline)

# fill a matrix by row with m0 rows and n0 columns
row.code <- '
   int m = Rcpp::as<int>(m0);
   int n = Rcpp::as<int>(n0);
   arma::mat mat = arma::zeros(m,n);
   arma::rowvec vec = Rcpp::as<arma::rowvec>(vec0);
   for (int i = 0; i < m; i++) {
      mat.row(i) = vec;
   }
   return Rcpp::wrap(mat);
'
row.f <-
cxxfunction(signature(m0="integer",n0="integer",vec0="numeric"),row.code,plugin="RcppArmadillo")

# so here we swap, fill by column, m0 is the number of columns and n0 is
the number of rows
col.code <- '
   int m = Rcpp::as<int>(m0);
   int n = Rcpp::as<int>(n0);
   arma::mat mat = arma::zeros(n,m);
   arma::colvec vec = Rcpp::as<arma::colvec>(vec0);
   for (int i = 0; i < m; i++) {
      mat.col(i) = vec;
   }
   return Rcpp::wrap(mat);
'
col.f <- cxxfunction(signature(m0="
integer",n0="integer",vec0="numeric"),col.code,plugin="RcppArmadillo")
user  system elapsed
  0.779   1.022   1.801
user  system elapsed
  0.957   0.966   1.922
[1] TRUE
user  system elapsed
  1.925   1.425   3.351
user  system elapsed
  1.244   1.423   2.667
[1] TRUE
On Wed, Mar 27, 2013 at 9:44 AM, Conrad S <conradsand.arma at gmail.com> wrote:

            
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://lists.r-forge.r-project.org/pipermail/rcpp-devel/attachments/20130327/fb13618d/attachment.html>