3

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?

  • 1
    Yes, sparse matrices are a bit more manual that way and the elegance of dense matrices and column-vector chunk ops goes away. But by doing all this 'cell-wise' work we managed to operate with really large ones. It's a trade-off. – Dirk Eddelbuettel Sep 16 '20 at 01:14
  • @DirkEddelbuettel thank you for your answer and all your work on Rcpp! I am still new to Rcpp-Armadillo, but I have read some stuff in the documentation on advanced constructors by which matrix memory can be allocated. Would it be possible to allocate the correct memory to x_subset before filling it to prevent unnecessary copies? The number of non-zero elements in each column of my full sp_mat is the same. – Etiënne Wijler Sep 16 '20 at 01:35
  • Again, that's for _dense_ matrices and yes we use to great effect. – Dirk Eddelbuettel Sep 16 '20 at 01:45

0 Answers0