I am writing a function to return a subset of the columns of a sparse matrix. The returned matrix is also sparse. For my first attempt, I first initialized a sparse matrix
Eigen::SparseMatrix<double> x_subset = col_sp(x, index)
with
Eigen::SparseMatrix<double> col_sp(const Eigen::SparseMatrix<double>& x, const std::vector<unsigned int>& index){
int n_cols=index.size();
Eigen::SparseMatrix<double> x_subset(x.rows(),n.cols());
for(int i=0; i!=x_subset.rows(); ++i){
x_subset.row(i)=x.row(index[i]);
}
return x_subset;
}
However, on compile, I got the following error message
error: static assertion failed: THIS_SPARSE_BLOCK_SUBEXPRESSION_IS_READ_ONLY
451 | EIGEN_STATIC_ASSERT(sizeof(T)==0, THIS_SPARSE_BLOCK_SUBEXPRESSION_IS_READ_ONLY);
I managed to get it working by declaring x_subset as Eigen::SparseMatrix<double> x_subset(x.rows(),n.cols());
and then passing it by reference into the following function:
void col_sp(Eigen::SparseMatrix<double>& x_subset,
const Eigen::SparseMatrix<double>& x,
const std::vector<unsigned int>& index) {
int n_cols = index.size();
for(int i=0; i!=x_subset.cols(); ++i){
x_subset.col(i) = x.col(index[i]);
}
}
I want to know if there is a way to get the first function working (i.e. return a SparseMatrix instead of passing the SparseMatrix by reference). I prefer the void function for this specific instance, but I would like to know why I received this error message and what, if anything, I can do to avoid it in the future.