2016-12-21 64 views
0

是否可以遍历矩阵并对某个子集进行一些分析?Rcpp循环和子集数字矩阵

在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但它失败。

+1

请转到[Rcpp Gallery](http://gallery.rcpp.org)并查看子集示例来回答此问题。简而言之:_sure!_ –

回答

4

没有理由在这里使用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] 

至于为什么

它几乎只是在一些后冻结关合作

发生的事情,你有一个出界访问这里

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

这是不确定的行为。你可能会说,“是的,但这是导致我的程序冻结的下一个行”,但那不是真的。您在前一行中做了非法行为,无论出于何种原因,注释行都是您“为此付费”的地方。