首页 > 解决方案 > 使用 RcppArmadillo 时调用 one 或 eye 函数失败

问题描述

我想使用oneeye函数Armadillo来构造矩阵或向量。但是,它不允许我这样做。这是一个示例代码:

#include <RcppArmadillo.h>

// [[Rcpp::depends(RcppArmadillo)]]
using namespace Rcpp;
// [[Rcpp::export]]
SEXP Generate(arma::mat Mat){
arma::mat Mat_2 = ones<mat>(5,6);
}

错误信息让我想起use of undeclared idenfier of 'mat'. 当我删除<mat>时,另一个按摩说use of undeclared idenfier of 'ones'

我查找了包含该ones功能的犰狳教程。我想知道为什么我的代码无法调用它。我错过了什么?

标签: rcpprcpparmadillo

解决方案


你的代码有几个问题:

  • 为什么要回来SEXP?使用类型对您有利
  • Mat如果你不使用它为什么要传入?
  • return声明
  • 名称空间的使用有点松散。

清理后的版本如下:

#include <RcppArmadillo.h>

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

// [[Rcpp::export]]
arma::mat Generate(int n=5, int k=6){
    arma::mat m = arma::ones<arma::mat>(n,k);
    return m;
}

/*** R
Generate()
*/

它编译并运行良好:

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

> Generate()
     [,1] [,2] [,3] [,4] [,5] [,6]
[1,]    1    1    1    1    1    1
[2,]    1    1    1    1    1    1
[3,]    1    1    1    1    1    1
[4,]    1    1    1    1    1    1
[5,]    1    1    1    1    1    1
> 

推荐阅读