简体   繁体   中英

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?

You can't store classes or structs as coefficients of an Eigen::SparseMatrix . The constructor of the Eigen::SparseMatrix is of the type

Eigen::SparseMatrix< _Scalar, _Options, _StorageIndex >::SparseMatrix ( )   

This means that an Eigen::SparseMatrix can only be used to store scalar coefficients. The scalar types that can be used are any numeric type, such as float , double , int or std::complex<float> , etc., as described here .

It is not clear why you would want to store anything else than a scalar type as coefficients of a SparseMatrix, since sparse matrices are used for arithmetic operations. But if you really want to address the structs via a SparseMatrix, you could instead prepare an array of structs of the type StructElem and store the indices of this array into an Eigen::SparseMatrix<int> .

As @RHertel noticed, Eigen::SparseMatrix is intended to be used for types which behave like Scalar types. Eg, 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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM