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

只谈情不闲聊 提交于 2019-12-11 01:18:40

问题


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?


回答1:


After the insert statement add this statement:

  new_mat.makeCompressed();


来源:https://stackoverflow.com/questions/26694446/rcppeigen-sparse-matrix-insert-operation-gives-invalid-class-dgcmatrix-error

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!