gpt4 book ai didi

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

转载 作者:太空宇宙 更新时间:2023-11-04 15:56:18 25 4
gpt4 key购买 nike

我是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/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com