2016-07-08 109 views
-1

我無法弄清楚如何在Rcpp中存儲距離矩陣。R - 在Rcpp中存儲距離矩陣

讓我們想象一下,我想存儲以下功能n*n個人的距離矩陣(我不方的sum因爲我不確定如何在rcpp這樣做。

distxy = function(x,y) sum (x - y) 

在這例如,我要兩兩比較3個個人

 [,1] [,2] [,3] [,4] 
[1,] 24 24 22 20 
[2,] 21 24 30 20 
[3,] 44 34 41 13 

R我將通過這樣

矩陣循環功能
mat = matrix(0, nrow(d), nrow(d)) 

    len = nrow(d) 
    mat = matrix(0, len, len) 

    for(j in 1:len){ 
    for(i in 1:len){ 
     mat[j,i] = distxy(d[j,], d[i,]) 
    } 
    } 

,並得到(我能夠勇敢地正視的結果,但是這不重要這裏)

 [,1] [,2] [,3] 
[1,] 0 -5 -42 
[2,] 5 0 -37 
[3,] 42 37 0 

我有我取得了什麼至今麻煩做同樣的rcpp

// [[Rcpp::export]] 
NumericVector FunCpp(NumericMatrix x) { 
    int nrow = x.nrow(); 
    NumericMatrix out(nrow); 

    for (int i = 0; i < nrow; i++) { 
    for (int j = 0; j < nrow; j++) { 
     out[i,j] = sum(x(i,_) - x(j,_)) ; 
    } 
    } 
    return out; 
} 

但距離矩陣不正確。任何想法 ?

d = rbind(c(24, 24, 22, 20), 
     c(21, 24, 30, 20), 
     c(44, 34, 41, 13)) 
+2

請不要濫用的StackOverflow作爲C++輔導服務。這是短時間內顯示_elementary_錯誤的第二個問題。我認爲在開始更加雄心勃勃的Rcpp冒險之前,你可能需要刷新你的C++。 –

回答

4

有一對夫婦的語法錯誤在你RCPP代碼:

  • 返回一個NumericVector而不是NumericMatrix
  • 使用operator[]索引由兩個維度(out[i,j]

這是一個清理版本:

#include <Rcpp.h> 

inline double distxy(Rcpp::NumericVector x, Rcpp::NumericVector y) { 
    return Rcpp::sum(x - y); 
} 

// [[Rcpp::export]] 
Rcpp::NumericMatrix FunCpp(Rcpp::NumericMatrix x) { 
    int nrow = x.nrow(); 
    Rcpp::NumericMatrix out(nrow); 

    for (int i = 0; i < nrow; i++) { 
     for (int j = 0; j < nrow; j++) { 
      out(j, i) = distxy(x.row(j), x.row(i)); 
     } 
    } 

    return out; 
} 

測試對你的一個R函數,

m <- matrix(
    c(24, 24, 22, 20, 
     21, 24, 30, 20, 
     44, 34, 41, 13), 
    nrow = 3, byrow = TRUE 
) 

all.equal(FunR(m), FunCpp(m)) 
#[1] TRUE 

至於平方,你可以使用std::powdistxy內,

return std::pow(Rcpp::sum(x - y), 2); 

或內部的FunCpp在你的內心循環:

out(j, i) = std::pow(distxy(x.row(j), x.row(i)), 2); 

distxy <- function(x,y) sum(x - y) 

FunR <- function(d) { 
    len <- nrow(d) 
    mat <- matrix(0, len, len) 

    for(j in 1:len){ 
     for(i in 1:len){ 
      mat[j,i] <- distxy(d[j,], d[i,]) 
     } 
    } 
    mat 
} 
+0

非常感謝。我真的很感激。我真的有'C++'的麻煩。 – giacomo