Rcpp NumericMatrix - how to erase a row / column?

自作多情 提交于 2019-11-30 19:48:13

How about using RcppArmadillo? I think the intention of the code would be much clearer...

#include <RcppArmadillo.h>
// [[Rcpp::depends(RcppArmadillo)]]

using namespace arma;

// [[Rcpp::export]]
mat sub1( mat x, uword e) {
  x.shed_col(e-1);
  x.shed_row(e-1);
  return x;
}

/*** R
sub1( matrix(1:9,3), 2 )
*/

> sub1( matrix(1:9,3), 2 )
     [,1] [,2]
[1,]    1    7
[2,]    3    9

Yes, both of these do work (fixing my typos above). I got a conversion error trying to replace int iter with Rcpp::NumericMatrix::iterator iter though. Any fix for this?

Note that we do not need the row_erase(NumericMatrix& x, int& ref) since this is a special case of row_erase(NumericMatrix& x, IntegerVector& ref).

NumericMatrix row_erase (NumericMatrix& x, IntegerVector& rowID) {
  rowID = rowID.sort();

  NumericMatrix x2(Dimension(x.nrow()- rowID.size(), x.ncol()));
  int iter = 0; 
  int del = 1; // to count deleted elements
  for (int i = 0; i < x.nrow(); i++) {
    if (i != rowID[del - 1]) {
      x2.row(iter) = x.row(i);
      iter++;
    } else {
      del++;
    }
  }
  return x2;
}

NumericMatrix col_erase (NumericMatrix& x, IntegerVector& colID) {
  colID = colID.sort();

  NumericMatrix x2(Dimension(x.nrow(), x.ncol()- colID.size()));
  int iter = 0; 
  int del = 1; 
  for (int i = 0; i < x.ncol(); i++) {
    if (i != colID[del - 1]) {
      x2.col(iter) = x.column(i);
      iter++;
    } else {
      del++;
    }
  }
  return x2;
}
标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!