c – Rcpp NumericMatrix – 如何擦除行/列?

前端之家收集整理的这篇文章主要介绍了c – Rcpp NumericMatrix – 如何擦除行/列?前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
我学习Rcpp类/数据结构时的新手问题:是否有成员函数来擦除类Rcpp :: NumericMatrix对象的行/列? (或其他类型的**矩阵 – 我假设它是一个模板类)?
library(Rcpp)
cppFunction('
  NumericMatrix sub1 {NumericMatrix x,int& rowID,int& colID) {
    // let's assume separate functions for rowID or colID
    // but for the example case here
    x.row(rowID).erase(); // ??? does this type of member function exist?
    x.col(colID).erase(); // ???
    return x;
}')

如果这种类型的成员函数不存在,那么这个怎么样?

cppFunction('NumericMatrix row_erase (NumericMatrix& x,int& rowID) {
  // a similar function would exist for removing a column.
  NumericMatrix x2(Dimension(x.nrow()-1,x.ncol());
  int iter = 0; // possibly make this a pointer?
  for (int i = 0; i < x.nrow(); i++) {
    if (i != rowID) {
      x2.row(iter) = x.row(i);
      iter++;
    }
  }
  return x2;
}')

或者我们希望删除一组行/列:

cppFunction('NumericMatrix row_erase (NumericMatrix& x,IntegerVector& rowID) {
  // a similar function would exist for removing a column.
  rowID = rowID.sort();

  NumericMatrix x2(Dimension(x.nrow()- rowID.size(),x.ncol());
  int iter = 0; // possibly make this a pointer?
  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;
}')

解决方法

使用RcppArmadillo怎么样?我认为代码的意图会更清楚……
#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,2 )
     [,1] [,2]
[1,]    1    7
[2,]    3    9

猜你在找的C&C++相关文章