Home > Software engineering >  C Eigen, how to multiply a sparse matrix and a dense vector?
C Eigen, how to multiply a sparse matrix and a dense vector?

Time:11-04

I am trying the following:

Eigen::SparseMatrix<double> bijection(2 * face_count, 2 * vert_count);
/* initialization */
Eigen::VectorXd toggles(2 * vert_count);
toggles.setOnes();
Eigen::SparseMatrix<double> deformed;
deformed = bijection * toggles;

Eigen is returning an error claiming:

 error: static assertion failed: THE_EVAL_EVALTO_FUNCTION_SHOULD_NEVER_BE_CALLED_FOR_DENSE_OBJECTS
  586 |       EIGEN_STATIC_ASSERT((internal::is_same<Dest,void>::value),THE_EVAL_EVALTO_FUNCTION_SHOULD_NEVER_BE_CALLED_FOR_DENSE_OBJECTS);

According to the eigen documentaion

Sparse matrix and vector products are allowed. What am I doing wrong?

CodePudding user response:

The problem is you have the wrong output type for that product.

The Eigen documentations says the following type of multiplication is legal:

dv2 = sm1 * dv1;

Sparse matrix times dense vector equals dense vector.

If you actually do need a sparse representation, I think there is no better way of getting one than performing the multiplication as above and then converting the product to a sparse matrix with the sparseView member function. e.g.

Eigen::SparseMatrix<double> bijection(2 * face_count, 2 * vert_count);
/* initialization */
Eigen::VectorXd toggles(2 * vert_count);
toggles.setOnes();
Eigen::VectorXd deformedDense = bijection * toggles;
Eigen::SparseMatrix<double> deformedSparse = deformedDense.sparseView();
  • Related