Rcpp: 无法在循环中创建 return 对象

Rcpp: cannot return object created in loop

我想我遗漏了一些相当基本的东西,但我不知道是什么:

    #include <Rcpp.h>
    using namespace Rcpp;
    // [[Rcpp::export]]

    NumericMatrix test(NumericVector x) {

    for(int i=0; i<100; i++)
    {
              NumericMatrix n_m1(4,5);
    }
    return n_m1;
    }

这给了我错误:

第 17 行 'n_m1' 未在此范围内声明

第19行控制到达非空函数的结尾[-Wreturn-type]

第一个错误显然是无稽之谈。它与循环有关,因为如果我删除它,它工作得很好。

非常感谢任何帮助!

这个变量的作用域(n_m1):

for(int i=0; i<100; i++)
{
              NumericMatrix n_m1(4,5);
}

循环。所以当然在循环之外你不能使用它。 return 都不是。

要扩展在方法级别定义的范围:

NumericMatrix test(NumericVector x) {
    NumericMatrix n_m1(4,5);

    for(int i=0; i<100; i++)
    {
      // you can use it here now
    }

    return n_m1; // also here
    }

我在上面定义变量的方式现在它具有函数范围 - 例如,您只能在函数内部使用它。如果想进一步扩大范围,或许可以考虑全局变量?如果有兴趣,您可以阅读有关该主题的更多信息,例如 here