Question

If I set the value of a SparseMatrix entry in Eigen as follows:

sparse_matrix->coeffref(10, 10) = 0;

Would this actually shrink the storage required by the matrix or would it try and store a 0 and use up 4 bytes there (assuming integer type)?

if the answer is the latter, how can I set columns to 0, so that it does not use any extra space?

Also, what about something like this:

typedef Eigen::Triplet<double> TripletType;
std::vector<TripletType> t;
for (int i = 0; i < some_value; ++i) {
    for (int j = 0; j < some_value; ++j) {
        t->push_back(TripletType(i, j, 0);
    }
}
sparse_matrix->setFromTriplets(t);

Would this result in explicit zeros in the sparse matrix?

Was it helpful?

Solution

After insertion with coeffRef you can prune the sparse matrix like:

Eigen::SparseMatrix<double, Eigen::ColMajor> A(5,5);
// fill A
A.insert(0,0)=9.;
A.insert(1,0)=3.0/2.0;
A.insert(0,1)=3.0/2.0;
A.insert(2,0)=6.0;
A.insert(0,2)=6.0;
A.insert(3,0)=3.0/4.0;
A.insert(0,3)=3.0/4.0;
A.insert(4,0)=3.0;
A.insert(0,4)=3.0;
A.insert(1,1)=1.0/2.0;
A.insert(2,2)=12.0;
A.insert(3,3)=5.0/8.0;
A.insert(4,4)=16.0;

std::cout << A << std::endl;
std::cout << A.data().size() << std::endl;

A.coeffRef(3,0) = 0;
A.prune(0,0);  // Suppresses all nonzeros which are much smaller than reference under the tolerence epsilon

std::cout << A << std::endl;
std::cout << A.data().size() << std::endl;`

Output:

Nonzero entries:
(9,0) (1.5,1) (6,2) (0.75,3) (3,4) (_,_) (_,_) (_,_) (1.5,0) (0.5,1) (6,0) (12,2
) (0.75,0) (0.625,3) (3,0) (16,4)

Outer pointers:
0 8 10 12 14  $
Inner non zeros:
5 2 2 2 2  $

9 1.5 6 0.75 3
1.5 0.5 0 0 0
6 0 12 0 0
0.75 0 0 0.625 0
3 0 0 0 16

16
Nonzero entries:
(9,0) (1.5,1) (6,2) (3,4) (1.5,0) (0.5,1) (6,0) (12,2) (0.75,0) (0.625,3) (3,0)
(16,4)

Outer pointers:
0 4 6 8 10  $

9 1.5 6 0.75 3
1.5 0.5 0 0 0
6 0 12 0 0
0 0 0 0.625 0
3 0 0 0 16

12

You can see that the size has changed from 16 to 12, as also the three (_,_) are removed.

I didn't check with sizeof() if memory storage that is needed is really less.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top