使用rcpp的简单矩阵到矩阵函数

时间:2016-11-07 15:52:29

标签: r rcpp

我试图使用rcpp在r中编写一个简单的函数。我通过http://adv-r.had.co.nz/Rcpp.html计算出语法,并使用了糖函数,却无法使用以下函数:

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;
}')

基本上是在矩阵的每个元素中应用函数。我怎样才能让它起作用?

1 个答案:

答案 0 :(得分:2)

不幸的是,Rcpp NumericMatrix尚不支持矩阵乘法。一种选择是通过Armadillo使用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")

注意%是逐元素乘法

相关问题