Search code examples
rcpparmadillo

An error with a three dimensional field (of vectors) in rcpp armadillo


I am trying to create a field in rcpp arma due to more than three iterations, but got an error. As an example, see the following simple code:

//[[Rcpp::export]]
field<vec> testgg(int k, int h, int g){
  field<vec> res(k, h, g);
  return(res);
}

I do nothing in this code, so this code should give me something. However, I got an error when I do this function like this.

> testgg(3,4,5)
Error in testgg(3, 4, 5) : 
  dims [product 12] do not match the length of object [60]
> testgg(3,4,1)
     [,1]      [,2]      [,3]      [,4]     
[1,] numeric,0 numeric,0 numeric,0 numeric,0
[2,] numeric,0 numeric,0 numeric,0 numeric,0
[3,] numeric,0 numeric,0 numeric,0 numeric,0

My guess is that the rcpp does not get this three dimensional field, but can get the field up to 2 dimensions. Why does this happen and how can I get a three dimensional field?


Solution

  • Please see the open issue #263 and maybe also other ones. There was a bug, there is a fix, but you currently need to set a #define to enable the fix (as we need to sort out if this has side-effects on other packages assuming the current behaviour).

    So in short do for example

    > Sys.setenv(PKG_CPPFLAGS="-DRCPP_ARMADILLO_FIX_Field")  ## sets #define RCPP_ARMADILLO_FIX_Field
    > Rcpp::cppFunction("arma::field<arma::vec> testgg(int k, int h, int g) { arma::field<arma::vec> res(k, h, g); return(res);}", depends="RcppArmadillo")
    > testgg(2,3,4)
    , , 1
    
         [,1]      [,2]      [,3]     
    [1,] numeric,0 numeric,0 numeric,0
    [2,] numeric,0 numeric,0 numeric,0
    
    , , 2
    
         [,1]      [,2]      [,3]     
    [1,] numeric,0 numeric,0 numeric,0
    [2,] numeric,0 numeric,0 numeric,0
    
    , , 3
    
         [,1]      [,2]      [,3]     
    [1,] numeric,0 numeric,0 numeric,0
    [2,] numeric,0 numeric,0 numeric,0
    
    , , 4
    
         [,1]      [,2]      [,3]     
    [1,] numeric,0 numeric,0 numeric,0
    [2,] numeric,0 numeric,0 numeric,0
    
    > 
    

    So if you compile with the correct flag, the field dimension is not reduced down.

    Edit And maybe you wanted cube instead of field ?

    > Rcpp::cppFunction("arma::cube testhh(int k, int h, int g) { arma::cube res(k, h, g); return(res);}", depends="RcppArmadillo")
    > testhh(4,3,2)
    , , 1
    
         [,1] [,2] [,3]
    [1,]    0    0    0
    [2,]    0    0    0
    [3,]    0    0    0
    [4,]    0    0    0
    
    , , 2
    
         [,1] [,2] [,3]
    [1,]    0    0    0
    [2,]    0    0    0
    [3,]    0    0    0
    [4,]    0    0    0
    
    >