Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
690 views
in Technique[技术] by (71.8m points)

c++ - RcppArmadillo sample on armadillo vector classes

We have been using the sample function from RcppArmadillo to randomly sample a NumericVector object. However, we have noticed that it isn't possible to use the same function on Armadillo types (vec or uvec). We have looked at the function definitions from the sample.h file and it looks like a templated function that should be able to work with these types, but we haven't been able to figure out how to make it work with Armadillo classes without doing a lot of conversions to and from the NumericVector or IntegerVector types from the Rcpp library.

For example, we have this function written in a file called try.cpp.

// [[Rcpp::depends(RcppArmadillo)]]
#include <RcppArmadillo.h>
#include <RcppArmadilloExtensions/sample.h>

using namespace arma;
using namespace Rcpp;

// [[Rcpp::export]]
arma::uvec sample_index(const int &size){
    arma::uvec sequence = linspace<uvec>(0, size-1, size);
    arma::uvec out = sample(sequence, size, false);
    return out;
}

Running the code above yields the following errors:

src/try.cpp|11 col 22 error| no matching function for call to 'sample' [cpp/gcc]      

~/Library/R/3.3/library/Rcpp/include/Rcpp/sugar/functions/sample.h|401 col 1 error| note: candidate function not viable: no known conversion from 'arma::uvec' (aka 'Col<unsigned int>') to 'int' for 1st argument [cpp/gcc]

~/Library/R/3.3/library/Rcpp/include/Rcpp/sugar/functions/sample.h|437 col 1 error| note: candidate template ignored: could not match 'Vector' against 'Col' [cpp/gcc]

Any help on this would be greatly appreciated :)

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

In case anyone runs into this problem in the future, the problem seems to have something to do with multiple definitions of the sample function in the namespaces being used. Specifically typing out the namespaces where the required function is defined solves the problem. In particular, the sample function needs to be called from Rcpp::RcppArmadillo.

The following code works as desired.

// [[Rcpp::depends(RcppArmadillo)]]
#include <RcppArmadillo.h>
#include <RcppArmadilloExtensions/sample.h>

// [[Rcpp::export]]
arma::uvec sample_index(const int &size){
    arma::uvec sequence = arma::linspace<arma::uvec>(0, size-1, size);
    arma::uvec out = Rcpp::RcppArmadillo::sample(sequence, size, false);
    return out;
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...