2016-11-28 59 views
1

我想创建通过RCPP在R.使用mappedsparsematrix型我选择mappedsparsematrix而不是稀疏矩阵,因为我想用它在R然后进一步计算的稀疏矩阵来初始化mappedsparsematrix。如果我在这一点上错了,请纠正我。如何使用RCPP

这是我在cpp的代码形式

// [[Rcpp::depends(RcppEigen)]] 
# include <RcppEigen.h> 
# include <Rcpp.h> 
# include <math.h> 
# include <list> 

using namespace Rcpp; 
using Eigen::SparseMatrix; 
using Eigen::MappedSparseMatrix; 
using Eigen::MatrixXd; 
using Eigen::VectorXi; 
typedef Eigen::VectorXd Vd; 
typedef Eigen::VectorXi Vi; 
typedef Eigen::MappedSparseMatrix<double> MSpMat; 
typedef MSpMat::InnerIterator InIterMat; 
typedef List list; 
typedef Eigen::Triplet<double> T; 


double euclidean_distance(double lon1, double lat1,double lon2,double lat2){ 
    double s = pow((lon1 - lon2),2) + pow((lat1 - lat2),2); 
    double ed = sqrt(s); 
    return(ed); 
} 


// [[Rcpp::export]] 
MSpMat mymain(NumericVector lat, NumericVector lon){ 
    std::list<T> L; 

    int length = lat.size(); 
    int index = 0; 
    for (int i = 0; i < length - 1; i++){ 
     for (int j = i+1; j < length; j++){ 
     double lon1 = lon[i]; 
     double lon2 = lon[j]; 
     double lat1 = lat[i]; 
     double lat2 = lat[j]; 
     double dist = euclidean_distance(lon1,lat1,lon2,lat2); 
     dist = exp(-dist/0.001); 
     if (dist > 0.01){ 
      L.push_back(T(index, i, dist)); 
      L.push_back(T(index, j, -dist)); 
     } 

     } 
    } 
    int nrows = L.size()/2; 
    int ncols = length; 

    MSpMat D(nrows, ncols); 
    D.setFromTriplets(L.begin(), L.end()); 
    return(D); 
} 

然而,当我尝试源cpp文件中R.

no matching constructor for initialization of "MSpMat" 

任何人的帮助可以修复它,它返回这个错误?

回答

3

好的,完整的错误是:

temp_eigen.cpp:51:10: error: no matching constructor for initialization of 'MSpMat' (aka 'MappedSparseMatrix') MSpMat D(nrows, ncols); ^~~~~~~~~~~~~

note: candidate constructor (the implicit copy constructor) not viable: requires 1 argument, but 2 were provided class MappedSparseMatrix ^

note: candidate constructor not viable: requires 6 arguments, but 2 were provided inline MappedSparseMatrix(Index rows, Index cols, Index nnz, Index* outerIndexPtr, Index* innerIndexPtr, Scalar* valuePtr)

从根本上说,错误在这里试图使用需要预先存在的存储单元中的数据类型和定义它,如果它不(例如两一步加载)。

更改:

MSpMat D(nrows, ncols); 

到:

typedef Eigen::SparseMatrix<double> SpMat; 
SpMat D(nrows, ncols); 

产生所期望的结果。

另一种方法是提供的一种形式:

MSpMat(Index rows, Index cols, Index nnz, 
     Index* outerIndexPtr, Index* innerIndexPtr, 
     Scalar* valuePtr) 
+0

非常好做。 –