René Schou René Schou - 1 month ago 25
R Question

Simple matrix to matrix function using rcpp

I'm trying to code a simple function in r using rcpp. I'm figuring out the syntax through http://adv-r.had.co.nz/Rcpp.html and used the sugar functions but could not get the following to work:

cppFunction('NumericMatrix fun(NumericMatrix x) {
NumericMatrix dd = (exp(-(pow(x, 2)) / 2)*(3 - 6*pow(x, 2) + pow(x,4)))/sqrt(2*PI);
return dd;
}')


Basically to apply a function in each element of a matrix. How can I make it to work?

Answer

Unfortunately, matrix multiplication is not yet supported for Rcpp NumericMatrix. One option is to use Armadillo via RcppArmadillo.

# install.packages("RcppArmadillo")
Rcpp::cppFunction('arma::mat fun(const arma::mat& x) {
    arma::mat dd = (exp(-(pow(x, 2)) / 2)%(3 - 6*pow(x, 2) + pow(x,4)))/sqrt(2*PI);
    return dd;
}', depends = "RcppArmadillo")

Note % is the element-wise multiplication