Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
402 views
in Technique[技术] by (71.8m points)

c++ - Rcpp NumericMatrix - how to erase a row / column?

A novice question as I learn the Rcpp classes / data structures: Is there a member function to erase a row / column for an object of class Rcpp::NumericMatrix? (Or other types of type **Matrix -- I'm assuming it's a template class)?

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;
}')

If this type of member function doesn't exist, how about this?

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;
}')

Or perhaps we wish to remove a set of rows/columns:

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;
}')
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...