我傳遞小稀疏矩陣(用於測試),以一個C++從R.函數矩陣屬於類dgCMatrix,如下所示:迭代非零元素本徵
5 x 5 sparse Matrix of class "dgCMatrix"
[1,] . . . . .
[2,] 1 1 . . .
[3,] . . . . .
[4,] . . 1 . .
[5,] . 1 . . .
我迭代這個矩陣在文檔here中提到。 我的函數輸出迭代器的值和行索引,列索引。
C++函數被定義如下:
#include <RcppEigen.h>
// [[Rcpp::depends(RcppEigen)]]
using Eigen::MappedSparseMatrix;
using Eigen::SparseMatrix;
using Eigen::VectorXi;
using Eigen::Map;
using namespace Rcpp;
using namespace std;
// [[Rcpp::export]]
void createRec(RObject sparse_mat, IntegerVector sparse_vec) {
const MappedSparseMatrix<int> spmat(as<MappedSparseMatrix<int> >(sparse_mat));
long int nrow = spmat.rows();
long int ncol = spmat.cols();
NumericVector sim(nrow);
for(int k=0;k<spmat.outerSize();k++){
for(SparseMatrix<int,Eigen::ColMajor>::InnerIterator it(spmat,k);it;++it){
cout<<"k="<<k<<endl;
cout<<"value="<<it.value()<<endl;
cout<<"it.row="<<it.row()<<endl;
cout<<"it.col="<<it.col()<<endl;
cout<<"index="<<it.index()<<endl;
}
}
}
對於上面的結果如下給出的矩陣被印刷:
k=0
value=156148016
it.row=66211520
it.col=0
index=66211520
k=1
value=0
it.row=0
it.col=1
index=0
k=1
value=1
it.row=4
it.col=1
index=4
k=2
value=1
it.row=3
it.col=2
index=3
1)不限於對應於k = 0的值的解釋?這些可能是由於以錯誤的方式傳遞矩陣?
2.)k正在迭代outerSize,它等於5,爲什麼它不迭代k = 3,4?考慮到它是一個sparseMatrix,這個行爲是來自迭代器的。
如果我將spmat的聲明更改爲:const SparseMatrix spmat(如>(sparse_mat));該問題在k = 0時解決。但我仍然不知道它的原因。 –
TUSHAr