Search code examples
c++eigen

Eigen virtually extend sparse matrix


I have a dense matrix A of size 2N*N that has to be multiplied by a matrix B, of size N*2N.

Matrix B is actually a horizontal concatenation of 2 sparse matrices, X and Y. B requires only a read-only access.

Unfortunately for me, there doesn't seem to be a concatenate operation for sparse matrices. Of course, I could simply create a matrix of size N*2N and populate it with the data, but this seems rather wasteful. It seems like there could be a way to group X and Y into some sort of matrix view.

Additional simplification in my case is that either X or Y is a zero matrix.


Solution

  • If your result matrix is column major (the default), you can assign partial results to vertical sub-blocks like so (if X or Y is structurally zero, the corresponding sub-product is calculated in O(1)):

    typedef Eigen::SparseMatrix<float> SM;
    
    void foo(SM& out, SM const& A, SM const& X, SM const &Y)
    {
        assert(X.rows()==Y.rows() && X.rows()==A.cols());
    
        out.resize(A.rows(), X.cols()+Y.cols());
    
        out.leftCols(X.cols()) = A*X;
        out.rightCols(Y.cols()) = A*Y;
    }
    

    If you really want to, you could write a wrapper class which holds references to two sparse matrices (X and Y) and implement operator*(SparseMatrix, YourWrapper) -- but depending on how you use it, it is probably better to make an explicit function call.