Eigen convert dense matrix to sparse one

10,743

Solution 1

you can use the sparseView() method for that:

sparse = dense.sparseView();

and even specify a tolerance:

sparse = dense.sparseView(epsilon,reference);

Solution 2

Do you control the creation of the dense matrix?

If you don't then there is no way to do this without reading every matrix element to see if it is empty.

If you are creating the dense matrix yourself you could create a data structure to help convert it to sparse when you need to. You could for example store with each matrix row the number of non-null elements in that row. Then you could skip rows with 0 non-null elements, and you could stop the conversion of any row once you've seen as many non-null elements as the count tells you.

What extra data you store would be dependent on the types of sparse matrices you expect. A common sparse matrix pattern is dense submatrices floating in the sparse matrix. You could nontate those dense regions when you create the dense matrix. E.g. don't store an element count per row, but rather keep a list of non-null rectangular regions at certain x,y offsets.

Share:
10,743
Alberto
Author by

Alberto

Computer scientist, innovation addicted, technology dependent, agile enthusiast, proud developer, bug persecutor, hooked on Java and dozen other languages.

Updated on June 07, 2022

Comments

  • Alberto
    Alberto almost 2 years

    How to convert an Eigen::Matrix<double,Dynamic,Dynamic> to an Eigen::SparseMatrix<double> ? I'm looking for a better way instead of iterate through the dense matrix

  • gr4nt3d
    gr4nt3d over 5 years
    I am having a hard time navigating through the Eigen-reference and code. Would you mind adding links to the documentation and/or reference the folder/file where these functions can be found ?
  • ggael
    ggael over 5 years
    For the [documentation][eigen.tuxfamily.org/dox/], search for sparseView in the embedded search engine (top-right), for the source code grep sparseView Eigen/ -R will give you what you're looking for.