-1

I'm new to working with Eigen/Sparse. I'm trying to initialize a Eigen Sparse matrix with a (values, innerIndices, outerStarts) triplet. I see that there is an option to do this through a COO style triplet but not the one I mentioned.

I'm thinking of something like

Eigen::SparseMatrix<double> A(nrow,ncol);
A.valuePtr() = &values
A.innerIndexPtr() = &innerIndices
A.outerIndexPtr() = &outerStarts

I've tried

Eigen::SparseMatrix<double> A(nrow,ncol);
A.valuePtr() = &values
A.innerIndexPtr() = &innerIndices
A.outerIndexPtr() = &outerStarts

But it crashes with a segfault.

Homer512
  • 9,144
  • 2
  • 8
  • 25
  • Before posting their first question on stackoverflow.com, everyone should take the [tour], read the [help], understand all the requirements for a [mre] and [ask] questions here. Not doing any of this results in a poor quality question almost every time. It then gets downvoted, closed, and then deleted. Repeated low-quality questions may result in a temporary ban from asking new questions. – Sam Varshavchik Jan 21 '23 at 09:50

1 Answers1

1

Use the Map specialization for sparse matrices. Like this:

#include <Eigen/Sparse>

#include <iostream>

Eigen::SparseMatrix<double> make()
{
    double values[] = { 1., 2., 3., 4. };
    int inner[] = { 4, 3, 2, 1 }; // nonzero row indices
    int outer[] = { 0, 1, 2, 3, 4, 4 }; // start index per column + 1 for last col
    return Eigen::SparseMatrix<double>::Map(
        5 /*rows*/, 5 /*cols*/, 4 /*nonzeros*/, outer, inner, values);
}

int main()
{
    std::cout << make() << '\n';
}

prints

Nonzero entries:
(1,4) (2,3) (3,2) (4,1) 

Outer pointers:
0 1 2 3 4  $

0 0 0 0 0 
0 0 0 4 0 
0 0 3 0 0 
0 2 0 0 0 
1 0 0 0 0 

Note that I make a map but immediately copy it to a proper SparseMatrix in the return value.

Homer512
  • 9,144
  • 2
  • 8
  • 25