c++ - 如何在 Rcpp 中构建常量矩阵?

标签 c++ rcpp rcpparmadillo

我是Rcpp 用户,在我的cpp 文件中,我需要重复使用一个矩阵。我想定义一个常量矩阵,但我不知道该怎么做。

我曾经在 Rcpp 中定义了一个常量 double 类型变量,它对我来说效果很好。但是当我对矩阵重复相同的方式时,

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

const int a[3][4] = {  
  {0, 1, 2, 3} ,   /*  initializers for row indexed by 0 */
  {4, 5, 6, 7} ,   /*  initializers for row indexed by 1 */
  {8, 9, 10, 11}   /*  initializers for row indexed by 2 */
};

// [[Rcpp::export]]
double tf(arma::mat x){
  double aa=arma::sum(x+a);
  return(aa);
}

出现以下错误

enter image description here

最佳答案

您错过了(非常棒,真的)Armadillo documentation 的现有示例.

您错过了矩阵上的 sum() 返回 vector 。

在分配给标量时,您还错过了 as_scalar 的(必需)使用。

随后是您的代码的修改和修复版本,以及输出。

代码

#include <RcppArmadillo.h>

// [[Rcpp::depends(RcppArmadillo)]]

// -- for { } init below
// [[Rcpp::plugins(cpp11)]]

// [[Rcpp::export]]
arma::mat getMatrix() {
  const arma::mat a = { {0, 1, 2, 3} ,   /*  initializers for row indexed by 0 */
                        {4, 5, 6, 7} ,   /*  initializers for row indexed by 1 */
                        {8, 9, 10, 11}   /*  initializers for row indexed by 2 */
  };
  return a;
}

// [[Rcpp::export]]
double tf(arma::mat x){
  double aa = arma::as_scalar(arma::sum(arma::sum(x+x)));
  return(aa);
}

/*** R
tf( getMatrix() )
*/

输出

R> Rcpp::sourceCpp("~/git/stackoverflow/57105625/answer.cpp")

R> tf( getMatrix() )
[1] 132
R> 

关于c++ - 如何在 Rcpp 中构建常量矩阵?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57105625/

相关文章:

c++ - 无法在 openGL 片段着色器中正确检索 16 位整数

使用 boost::iostreams::gzip_decompress 时,rcpp 代码无法使用 boost 库加载(如在 BH 中实现)

c++ - 无法构建 RcppArmadillo.package.skeleton 测试包 : Multiple definition of `R_init_<name>'

c++ - UE4包装错误:OpenSSL链接问题

c++ - OpenWRT 的简单 Hello World 程序

c++ - 对高度依赖数学的用户编码的脚本或插件语言的建议?

r - 如何在 RCpp 中向数据框添加新列?

c++ - 调试可能的 Rcpp 内存泄漏时遇到问题

r - 有效地计算 R 中两个 3D 数组的叉积和