RcppEigen稀疏矩阵插入操作给出了无效的类“dgCMatrix”错误

时间:2014-11-01 23:42:04

标签: c++ r sparse-matrix rcpp

我试图快速使用C ++来快速构建一些用于R的稀疏矩阵。但是,我似乎无法使用insert方法更改Eigen中稀疏矩阵的单个元素并获取类dgCMatrix的正确R对象。下面是一个简单的例子。

C ++代码是:

#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;
}

结果R是:

> 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

从stdout可以看出,eigen正在做正确的事情。但是,生成的稀疏矩阵对象格式不正确。实际上,查看其插槽显示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()

任何想法可能出错?

1 个答案:

答案 0 :(得分:1)

insert语句后添加以下语句:

  new_mat.makeCompressed();