user3271788
user3271788

Reputation: 165

RcppEigen sparse matrix insert operation gives invalid class “dgCMatrix” error

I'm trying to get up to speed on using C++ to quickly build some sparse matrices for use in R. However, I cannot seem to use the insert method to change single elements of a sparse matrix in Eigen and get a correct R object of class dgCMatrix. A simple example is below.

The C++ code is:

#include <RcppEigen.h>

// [[Rcpp::depends(RcppEigen)]]
using Eigen::SparseMatrix;              // sparse matrix

// [[Rcpp::export]]
SparseMatrix<double> SimpleSparseMatrix(int n) {
  SparseMatrix<double> new_mat(n, n);
  new_mat.insert(0, 0) = 2;
  Rcpp::Rcout << new_mat << std::endl;
  return new_mat;
}

And the resulting R is:

> SimpleSparseMatrix(2)
2 0 
0 0 

2 x 2 sparse Matrix of class "dgCMatrix"
Error in validObject(x) : 
  invalid class “dgCMatrix” object: last element of slot p must match length of slots i and x

As you can see from stdout, eigen is doing the right thing. However, the resulting sparse matrix object is malformed. Indeed, looking at its slots show invalid values for p:

> foo <- SimpleSparseMatrix(2)
2 0 
0 0 

> str(foo)
Formal class 'dgCMatrix' [package "Matrix"] with 6 slots
  ..@ i       : int 0
  ..@ p       : int [1:3] 0 2 4
  ..@ Dim     : int [1:2] 2 2
  ..@ Dimnames:List of 2
  .. ..$ : NULL
  .. ..$ : NULL
  ..@ x       : num 2
  ..@ factors : list()

Any ideas what might be going wrong?

Upvotes: 2

Views: 615

Answers (1)

G. Grothendieck
G. Grothendieck

Reputation: 270075

After the insert statement add this statement:

  new_mat.makeCompressed();

Upvotes: 1

Related Questions