2

I don't understand the result I get when I try to iterate over valuePtr of a sparse matrix. Here is my code.

#include <iostream>
#include <vector>
#include <Eigen/Sparse>

using namespace Eigen;

int main()
{
  SparseMatrix<double> sm(4,5);

  std::vector<int> cols = {0,1,4,0,4,0,4};
  std::vector<int> rows = {0,0,0,2,2,3,3};
  std::vector<double> values = {0.2,0.4,0.6,0.3,0.7,0.9,0.2};

  for(int i=0; i < cols.size(); i++)
      sm.insert(rows[i], cols[i]) = values[i];

  std::cout << sm << std::endl;

  int nz = sm.nonZeros();
  std::cout << "non_zeros : " << nz << std::endl;

  for (auto it = sm.valuePtr(); it != sm.valuePtr() + nz; ++it)
    std::cout << *it << std::endl;

  return 0;
}

Output:

0.2 0.4 0 0 0.6  // The values are in the matrix
0 0 0 0 0 
0.3 0 0 0 0.7 
0.9 0 0 0 0.2 

non_zeros : 7  
0.2            // but valuePtr() does not point to them
0.3            // I expected: 0.2, 0.3, 0.9, 0.4, 0.6, 0.7, 0.2
0.9
0
0.4
0
0

I don't understand why I am getting zeros, what's going on here?

1 Answer 1

3

According to the documentation for SparseMatrix:

Unlike the compressed format, there might be extra space inbetween the nonzeros of two successive columns (resp. rows) such that insertion of new non-zero can be done with limited memory reallocation and copies.

[...]

A call to the function makeCompressed() turns the matrix into the standard compressed format compatible with many library.

For example:

This storage scheme is better explained on an example. The following matrix

0  3  0   0   0
22 0  0   0   17
7  5  0   1   0
0  0  0   0   0
0  0  14  0   8

and one of its possible sparse, column major representation:

Values:       22  7   _   3   5   14  _   _   1   _   17  8
InnerIndices: 1   2   _   0   2   4   _   _   2   _   1   4

[...]

The "_" indicates available free space to quickly insert new elements.

Since valuePtr() simply return a pointer to the Values array, you'll see the empty spaces (the zeroes that got printed) unless you make the matrix compressed.

1
  • Thank You. If I do sm.makeCompressed() everything is as I expected.
    – Akavall
    Aug 6, 2014 at 20:30

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.