Rcpp 循环和子集数值矩阵

Rcpp Loop and Subset Numeric Matrix

是否可以遍历矩阵并对某些子集进行一些分析?

在 R 中:

for(i in 10:nrow(mat)){
   hist = mat[(i-5):(i),]
   // Do something
}

在上面的 R 示例中,我从第 10 行到最后一行遍历 mat 矩阵。在每次迭代中,我将最近的 5 个观察结果子集化并做一些事情。

这在 Rcpp 中可行吗?下面的例子是我试过的..

  int n_col = sample_data.ncol();
  int n_row= sample_data.nrow();
  int max_lb = 10;
  for( int i=(max_lb+1); i<n_row; i++) {

    SubMatrix<REALSXP> res = sample_data(Range(i-max_lb,i),Range(0,n_col));
    //NumericMatrix hist = res;  //If this is uncommented, it fails when I run it...it pretty much just freezes after some iteration...
    Rcpp::Rcout << "-----------------------------" <<std::endl;
    Rcpp::Rcout << i << "\n" <<std::endl;
    Rcpp::Rcout << res .nrow() <<std::endl; // Dimensions do not match what I have
    Rcpp::Rcout << res .ncol() <<std::endl;
  }

在行 //NumericMatrix hist = res; 中,我尝试将其转换回 NumericMatrix 类型,但失败了。

这里没有必要使用SubMat<>,子集运算的结果会直接转换为NumericMatrix

#include <Rcpp.h>

// [[Rcpp::export]]
void submat(Rcpp::NumericMatrix x, int max_lb = 10) {
    int n_col = x.ncol();
    int n_row = x.nrow();

    for (int i = max_lb + 1; i < n_row; i++) {
        Rcpp::NumericMatrix res =
            x(Rcpp::Range(i - max_lb, i), Rcpp::Range(0, n_col - 1));

        std::printf(
            "i = %d: [%d x %d]\n",
            i, res.nrow(), res.ncol()
        );
    }
}

submat(matrix(1:40, 20))
# i = 11: [11 x 2]
# i = 12: [11 x 2]
# i = 13: [11 x 2]
# i = 14: [11 x 2]
# i = 15: [11 x 2]
# i = 16: [11 x 2]
# i = 17: [11 x 2]
# i = 18: [11 x 2]
# i = 19: [11 x 2] 

至于为什么

it pretty much just freezes after some iteration

发生了,你在这里有越界访问

sample_data(Range(i-max_lb,i),Range(0,n_col));
//                            ^^^^^^^^^^^^^^^^

这是未定义的行为。您可能会说,"yes but it was the next line that caused my program to freeze",但事实并非如此。您在上一行中做了一些非法的事情,无论出于何种原因,注释掉的行都是您 "paid for it".