本文介绍了RcppEigen稀疏矩阵插入操作给出无效的类"dgCMatrix"错误的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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.

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

从标准输出中可以看到,本征正在做正确的事情.但是,所得的稀疏矩阵对象格式错误.确实,查看其插槽会显示p的无效值:

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?

推荐答案

insert语句之后添加以下语句:

After the insert statement add this statement:

  new_mat.makeCompressed();

这篇关于RcppEigen稀疏矩阵插入操作给出无效的类"dgCMatrix"错误的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

10-18 23:16