c++11rcpprcpparmadillo

arma::mat division by const integer causes problems


I have a function I call from R using Rcpp. I pass an argument, which is a const unsigned integer, to this function. The integer is used to scale a matrix consisting of random draws. MWE:

Rcpp::cppFunction('

auto testfun(const arma::uword n = 10)
{  
  arma::dmat W = floor(arma::randu(35, 35, arma::distr_param(0, 2)));
  return W / n;
}
', depends = "RcppArmadillo", plugins = "cpp17")

This MWE makes my R crash. My actual code, on the other hand, works but returns garbage. What am I missing here?

It appears that the auto declaration is causing the problems. I don't understand why.


Solution

  • Using the documented interfaces and types for which RcppArmadillo contains the templated converters turns your failing function into a working function.

    (Here I also scale the dims from 35 to 5 for more compact display. It works either way. I also add two linebreaks for the display here. )

    > Rcpp::cppFunction("arma::mat f(const int n = 10) { 
              arma::mat W = floor(arma::randu(5,5,arma::distr_param(0,2))); 
              return W / n; }", depends="RcppArmadillo") 
    > f() 
         [,1] [,2] [,3] [,4] [,5]
    [1,]  0.0  0.0  0.1  0.1  0.0
    [2,]  0.1  0.1  0.1  0.0  0.0
    [3,]  0.1  0.1  0.0  0.1  0.0
    [4,]  0.0  0.1  0.1  0.0  0.0
    [5,]  0.0  0.0  0.0  0.0  0.1
    > f(2) 
         [,1] [,2] [,3] [,4] [,5]
    [1,]  0.0  0.0  0.5  0.0  0.0
    [2,]  0.0  0.5  0.5  0.0  0.5
    [3,]  0.5  0.5  0.0  0.5  0.0
    [4,]  0.0  0.0  0.5  0.0  0.0
    [5,]  0.0  0.5  0.0  0.5  0.5
    >