Search code examples
c++sparse-matrixeigeneigen3

Subset columns of sparse eigen matrix


I want to take subset columns of some sparse matrix (column-major) As far as i know there are indexing stuff in Eigen. But i cannot call it for sparse matrix:

Eigen::SparseMatrix<double> m;
std::vector<int> indices = {1, 5, 3, 6};
// error: type 'Eigen::SparseMatrix<double>' does not provide a call operator
m(Eigen::all, indices); 

Is there are any workaround?

UPD1 Explicitly specified that columns can be in arbitrary order.


Solution

  • The SparseMatrix actually does not provide any operator(), so this cannot be done.

    EDIT: The following was aimed at an older version of the question.

    In case your actual use case also has the property that the columns you want to access are adjacent you can instead use

    SparseMatrix<double,ColMajor> m(5,5);
    int j = 1;
    int number_of_columns=2;
    m.middleCols(j,number_of_columns) = ...;
    

    There are also m.leftCols(number_of_columns) and m.rightCols(number_of_columns) These are even writable, because the matrix is column-major.

    All other block expressions are defined but read-only, see the corresponding Sparse Matrix documentation.

    EDIT: To answer the updated question: I guess you won't be able to avoid copying. With copying it can be done like this (not tested)

    Eigen::SparseMatrix<double> m;
    std::vector<int> indices = {1, 5, 3, 6};
    Eigen::SparseMatrix<double> column_subset(m.rows(),indices.size());
    for(int j =0;j!=column_subset.cols();++j){
    column_subset.col(j)=m.col(indices[j]);
    }