Search code examples
c++sparse-matrixeigen

Eigen SparseMatrix reserve nnz


I was wondering if the reserve method in Eigen does also allocate memory for the outer indices and inner indices (in a 3-CSC case.)

That means if I do

n = 1000
SparseMatrix<float> A;
A.reserve(n)

then

  • allocate n memory for data
  • allocate n memory for inner indices
  • allocate n+1 memory for outer indices (worst-case and a-priori not known)

The documentation says only

void Eigen::SparseMatrix<...>::reserve    (Index reserveSize) 

Preallocates reserveSize non zeros.

Precondition: the matrix must be in compressed mode.


Can anyone clarify this? Or tell something about the reservation policy? Thanks


Solution

  • No, the sizes of the matrix are supposed to be rather static, so reserve(n) allocates space for non-zeros only. If the dimension are unknown, you can start with an upper bound:

    SparseMatrix<float> A(n,n);
    

    reserve, e.g.:

    A.reserve(10*n);
    

    and once you're done and that you know the final size, shrink it:

    A.conservativeResize(rows,cols);