Search code examples
c++structsparse-matrixeigen

Create an Eigen sparse matrix with elements type of a struct


I would like to know if there is any way to define a sparse matrix as Eigen::SparseMatrix< StructElem >, which means each element of the matrix is an struct.

I tried the following code, but I got the error of "no suitable constructor exists to convert from int to StructElem".

// the structure of element:
    struct StructElem
    {
       unsigned int mInd;
       bool mIsValid;
       double mVec[ 4 ];
    };

// define the matrix:    
    Eigen::SparseMatrix< StructElem > lA( m, n);

// work with the matrix
    for( unsigned int i = 0; i < m; i++)
    {
       StructElem lElem;
       lElem.mInd = i;
       lElem.mIsValid = true;
       lElem.mVec= {0.0, 0.1, 0.2, 0.4};

       lA.coeffRef(i, i) = lElem; // got the error here!
    }

I was wondering if you would have any sort of ideas to solve this error?


Solution

  • As @RHertel noticed, Eigen::SparseMatrix is intended to be used for types which behave like Scalar types. E.g., the type should be constructable from 0, and it should be add-able and multiply-able (the latter is only required if you do actual linear algebra with it).

    You can fool Eigen to handle your custom type, by adding a constructor which takes an int (but ignores it):

    struct StructElem
    {
       unsigned int mInd;
       bool mIsValid;
       std::array<double,4> mVec;
       explicit StructElem(int) {}
       StructElem() = default;
    };
    

    Full demo: https://godbolt.org/z/7iPz5U