Rcpp does not support arrays yet (only vectors and matrices). However, RcppArmadillo has a proper 3D array class: arma::cube. The conversion can be done via Rcpp::NumericVector.
require(inline) require(RcppArmadillo) src <- ' using namespace Rcpp; NumericVector vecArray(myArray); IntegerVector arrayDims = vecArray.attr("dim");
arma::cube cubeArray(vecArray.begin(), arrayDims[0], arrayDims[1], arrayDims[2], false); //change one element in the array/cube cubeArray(0,0,0) = 518; return(wrap(cubeArray)); ' readCube = cxxfunction(signature(myArray="numeric"),body=src, plugin="RcppArmadillo")
A numerical test:
> set.seed(345) > testArray = array(rnorm(18), dim=c(3,3,2)) > print(testArray) , , 1 [,1] [,2] [,3] [1,] -0.7849082 -0.29059656 -0.927724 [2,] -0.2795144 -0.06753159 1.710771 [3,] -0.1614579 -0.63352041 1.654769 , , 2 [,1] [,2] [,3] [1,] 1.810483 -0.8496292 -1.4029422 [2,] 1.866772 0.3184496 0.5682982 [3,] -1.399833 0.9035913 1.0457561 > readCube(testArray) , , 1 [,1] [,2] [,3] [1,] 518.0000000 -0.29059656 -0.927724 [2,] -0.2795144 -0.06753159 1.710771 [3,] -0.1614579 -0.63352041 1.654769 , , 2 [,1] [,2] [,3] [1,] 1.810483 -0.8496292 -1.4029422 [2,] 1.866772 0.3184496 0.5682982 [3,] -1.399833 0.9035913 1.0457561
Thanks Vladimir, it is very useful! I'll try and do something similar with a complex cube (or complex matrices, if it does not work out).
ReplyDeleteRobert
Thanks for the post. fyi, vecArray.attr("dim") will get the dims attribute without passing it in.
ReplyDeleteEli
Thanks a bunch for the tip, Eli! Post is updated.
ReplyDeletePerfect Givenchy Handbags, combining elegant style and cutting-edge technology, a variety of styles of replica Givenchy t shirts, the pointer walks between your exclusive taste style.
ReplyDelete