[Rcpp-devel] Three-dimensional vectors example
Dirk Eddelbuettel
edd at debian.org
Mon Sep 24 20:50:10 CEST 2012
Someone just asked on StackOverflow about creating 3d arrays:
http://stackoverflow.com/questions/12569992/constructing-3d-array-in-rcpp
The best I could come up with is below. Did I miss something better?
Full disclosure: The last I needed this, I also needed ops on it, and used
the arma::cube class from (Rcpp)Armadillo instead.
Dirk
File:
library(inline)
fx <- cxxfunction(signature(vs="numeric", ds="integer"), plugin="Rcpp", body='
Rcpp::NumericVector v(vs); // get the data
Rcpp::Dimension d(ds); // get the dimension object
Rcpp::NumericVector r(d); // create (empty) vector with correct dims
std::copy(v.begin(), v.end(), r.begin()); // and copy
return Rcpp::List::create(v, d, r);
')
Output:
R> library(inline)
R> fx <- cxxfunction(signature(vs="numeric", ds="integer"), plugin="Rcpp", body='
+ Rcpp::NumericVector v(vs); // get the data
+ Rcpp::Dimension d(ds); // get the dimension object
+ Rcpp::NumericVector r(d); // create (empty) vector with correct dims
+ std::copy(v.begin(), v.end(), r.begin()); // and copy
+ return Rcpp::List::create(v, d, r);
+ ')
R> fx(1:8, c(2,2,2))
[[1]]
[1] 1 2 3 4 5 6 7 8
[[2]]
[1] 2 2 2
[[3]]
, , 1
[,1] [,2]
[1,] 1 3
[2,] 2 4
, , 2
[,1] [,2]
[1,] 5 7
[2,] 6 8
R>
--
Dirk Eddelbuettel | edd at debian.org | http://dirk.eddelbuettel.com
More information about the Rcpp-devel
mailing list