首页 > 解决方案 > 将 Matrix::sparseMatrix 传递给 Rcpp

问题描述

所以我对将稀疏矩阵从 R 传递到 c++ 的推荐方法感到非常困惑。我的印象是 sp_mat 是正确的参数类型,如下面的代码所示

testCode = '                                                                                                                                                                                                                                                           
#include <RcppArmadillo.h>                                                                                                                                                                                                                                             
// [[Rcpp::depends(RcppArmadillo)]]                                                                                                                                                                                                                                    

// [[Rcpp::export]]                                                                                                                                                                                                                                                    
void testFun(arma::sp_mat F){                                                                                                                                                                                                                                          

  Rcpp::Rcout << "F has " << F.n_rows << " rows" << std::endl;                                                                                                                                                                                                         

}'

Rcpp::sourceCpp(code = testCode)

n = 70000
M = Matrix::sparseMatrix(i=c(n), j=c(n), x=c(1))

testFun(M)

但是,运行此代码会产生以下错误:

error: SpMat::init(): requested size is too large
Error in testFun(M) : SpMat::init(): requested size is too large
Calls: testFun -> .Call
Execution halted

我在https://gallery.rcpp.org/articles/armadillo-sparse-matrix/中看到了这个例子,但我不确定它是否是说每次我们将稀疏矩阵传递给 c++ 时,我们应该使用那里提供的函数? 感谢您的澄清!

标签: rrcpprcpparmadillo

解决方案


好的,所以我想我找到了答案。如果元素总数大于存储元素数量的变量的大小,则基本上犰狳会抛出此错误,如下所示: https ://gitlab.com/conradsnicta/armadillo-code/-/blob/9.900.x /include/armadillo_bits/SpMat_meat.hpp

之前有人意识到这一点并在这里提供了一个解决方案: Large Matrices in RcppArmadillo via the ARMA_64BIT_WORD define


推荐阅读