Efficiently selecting non-contiguous columns of a sparse matrix in Rcpp-Armadillo

227 Views Asked by At

I am facing a seemingly simple task, but I am struggling to find an efficient way to do it. In Armadillo, I have defined a sparse matrix (sp_mat) of which I want to extract a number of non-contiguous columns. Unfortunately, sparse matrices do not support the non-contiguous view, so I have written my own function for it:

arma::sp_mat col_sp(const arma::sp_mat& x,const arma::uvec& index) {
int n_cols = index.n_elem;
arma::sp_mat x_subset(x.n_rows,index.n_elem);
for(int i=0; i<n_cols; i++){
    x_subset.col(i) = x.col(index(i));
}
return x_subset;}

However, I am worried that this function is making a new copy and/or reallocating memory each time I add a new column to x_subset. Is this indeed the case and, if so, is there a better way to obtain the desired submatrix?

0

There are 0 best solutions below