Search code examples
c++sparse-matrixeigen

sparse matrix from triplet


With eigen (c++) i want to have a similar result as Matlab's one :

 % Matlab code: Create a 1500-by-1500 sparse matrix from the triplets i, j, 
            and v 
 i = [900 1000];
   j = [900 1000];
   v = [10 100];
   S = sparse(i,j,v,1500,1500)

   %result
    S =

 (900,900)     10
 (1000,1000)   100

I want to do the same thing in C++, i saw in different posts that we can handle sparse matrices with Eigen Library, but i didn't really understand how to do this. Can you help me ?

Thanks


Solution

  • Create a vector of triplets

    typedef Eigen::Triplet<int> Trip;
    std::vector<Trip> trp;
    

    Create the triplets

    trp.push_back(Trip(900,900,10)); // (index, index, value)
    trp.push_back(Trip(1000,1000,100));
    

    Assign them to the sparse Eigen matrix

    int rows, cols;
    rows = cols = 1500;
    Eigen::SparseMatrix<int> A(rows,cols);
    
    A.setFromTriplets(trp.begin(), trp.end());
    

    Print the entire (dense) matrix

    std::cout << A << std::endl;
    

    or print just the indices and values

    std::cout << "Row\tCol\tVal" <<std::endl;
    for (int k=0; k < A.outerSize(); ++k)
    {
        for (SparseMatrix<int>::InnerIterator it(A,k); it; ++it)
        {
            std::cout << it.row() << "\t"; // row index
            std::cout << it.col() << "\t"; // col index (here it is equal to k)
            std::cout << it.value() << std::endl;
        }
    }