Xia*_*ong 0 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);
}
Run Code Online (Sandbox Code Playgroud)
它具有以下错误
您错过了(非常好,实际上)Armadillo文档中的现有示例。
您错过了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() )
*/
Run Code Online (Sandbox Code Playgroud)
R> Rcpp::sourceCpp("~/git/stackoverflow/57105625/answer.cpp")
R> tf( getMatrix() )
[1] 132
R>
Run Code Online (Sandbox Code Playgroud)