celestialgod

distance matrix

Mar 12th, 2016
207
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
R 1.37 KB | None | 0 0
  1. dis_multi <- function(x, y) rowSums(x != y)
  2. dis <- function(x, y) sum(x != y)
  3. x <- matrix(rbinom(30000, 3, 0.7), 3000, 10)
  4.  
  5. st <- proc.time()
  6. distMat <- matrix(0, nrow(x), nrow(x))
  7. for (i in 1:(nrow(x)-2))
  8.   distMat[i, (i+1):nrow(x)] <- dis_multi(x[(i+1):nrow(x), ], t(matrix(x[i,], ncol(x), nrow(x)-i)))
  9. distMat[nrow(x), nrow(x)-1] <- dis(x[nrow(x)-1, ], x[nrow(x), ])
  10. distMat <- distMat + t(distMat)
  11. proc.time() - st
  12. #   user  system elapsed
  13. #   1.10    0.04    1.16
  14.  
  15. st <- proc.time()
  16. distMat2 <- matrix(0, nrow(x), nrow(x))
  17. for (i in 1:(nrow(x)-1))
  18. {
  19.   for (z in (i+1):nrow(x))
  20.   {
  21.     distMat2[i, z] <- dis(x[i, ], x[z, ])
  22.   }
  23. }
  24. distMat2 <- distMat2 + t(distMat2)
  25. proc.time() - st
  26. #   user  system elapsed
  27. #  14.45    0.16   15.07
  28.  
  29. all.equal(distMat, distMat2) # TRUE
  30.  
  31. library(Rcpp)
  32. library(RcppArmadillo)
  33. sourceCpp(code = '
  34. // [[Rcpp::depends(RcppArmadillo)]]
  35. #include <RcppArmadillo.h>
  36. using namespace Rcpp;
  37. using namespace arma;
  38.  
  39. // [[Rcpp::export]]
  40. mat dis_cal_f(mat x) {
  41.  mat distMat(x.n_rows, x.n_rows);
  42.  for (uword i = 0; i < x.n_rows-1; i++)
  43.  {
  44.    for (uword j = i+1; j < x.n_rows; j++)
  45.      distMat(i, j) = sum(x.row(i) != x.row(j));
  46.  }
  47.  return symmatu(distMat);
  48. }')
  49.  
  50. st <- proc.time()
  51. distMat3 <- dis_cal_f(x)
  52. proc.time() - st
  53. #   user  system elapsed
  54. #   0.22    0.01    0.24
  55.    
  56. all.equal(distMat, distMat3) # TRUE
Advertisement
Add Comment
Please, Sign In to add comment