[Rcpp-devel] Initialize a matrix with a vector and the dimensions

Peng Yu pengyu.ut at gmail.com
Tue Aug 28 23:23:35 CEST 2012


On Tue, Aug 28, 2012 at 4:17 PM, Peng Yu <pengyu.ut at gmail.com> wrote:
> Hi,
>
> The closest thing that I can find to initialize a NumericMatrix with a
> NumericVector is the following constructor from Rcpp/vector/Matrix.h.
> But I need to see an example on how to use it. Does anybody have any
> example to share with me? Thanks!
>
>     template <typename Iterator>
>     Matrix( const int& nrows_, const int& ncols, Iterator start ) :

Just to clarify my original question, I want to convert from native R
vector to matrix directly (not through NumericVector). The following
code involves NumericVector. Does it result in extra copying of a
NumericVector?

> suppressPackageStartupMessages(library(inline))
> fun=cxxfunction(signature(mx='numeric')
+   , body='
+   Rcpp::NumericVector v(mx);
+   Rcpp::NumericMatrix mat(2, 3, v.begin());
+   return mat;
+   '
+   , plugin='Rcpp'
+   )
> orig=1:6
> fun(orig)
     [,1] [,2] [,3]
[1,]    1    3    5
[2,]    2    4    6

-- 
Regards,
Peng


More information about the Rcpp-devel mailing list