Search code examples
c++sparse-matrixeigen

How do I declare a vector of sparse matrix in Eigen


To declare a vector of dense matrix in Eigen I am using the following format

std::vector<Eigen::MatrixXd> AMAT(idx, Eigen::MatrixXd::Zero(1000,1000));

where idx is the vector size. Is there an equivalent declaration to define a sparse matrix? I am currently declaring a sparse matrix as

Eigen::SparseMatrix<double>  BMAT(1000,1000);

It will be more efficient for to me define a vector of such matrix instead of declaring separate sparse matrix for each index. Any help is appreciated.


Solution

  • Seeing you want the matrices in the vector to have differen sizes, you should probably not use that initialization constructor for std::vector.

    Instead just build-up the vector element by element:

    #include <Eigen/Sparse>
    #include <vector>
    #include <algorithm>
    
    int main() {
        auto sizes = { 100, 200, 300 };
    
        std::vector<Eigen::SparseMatrix<double>> BMATvec;
        BMATvec.reserve(sizes.size());
    
        std::transform(cbegin(sizes), cend(sizes), back_inserter(BMATvec),
            [](auto size) { return Eigen::SparseMatrix<double>(size,size);});
    }