如何在Rcpp中建立常数矩阵?

时间:2019-07-19 04:39:44

标签: c++ rcpp rcpparmadillo

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

我曾经在Rcpp中定义一个常数双精度类型变量,它对我来说很好用。但是当我对矩阵重复相同的方法时,

#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

1 个答案:

答案 0 :(得分:5)

您错过了(非常好)Armadillo documentation上的现有示例。

您错过了矩阵上的sum()返回一个向量。

在分配给标量时,您还错过了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> 
相关问题