gpt4 book ai didi

c++ - Rcpp NumericMatrix - 如何删除行/列?

转载 作者:可可西里 更新时间:2023-11-01 18:37:38 25 4
gpt4 key购买 nike

我学习 Rcpp 类/数据结构时的一个新手问题:是否有一个成员函数可以为 Rcpp::NumericMatrix 类的对象删除行/列? (或其他类型的 type **Matrix -- 我假设它是一个模板类)?

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,3), 2 )
[,1] [,2]
[1,] 1 7
[2,] 3 9

关于c++ - Rcpp NumericMatrix - 如何删除行/列?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33507695/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com