2016-11-28 58 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

非常好做。 –