Guest User

Untitled

a guest
Oct 19th, 2018
84
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 0.76 KB | None | 0 0
  1. require(inline)
  2. require(RcppArmadillo)
  3.  
  4. ## extract cosine similarity between columns
  5. cosine <- function(x) {
  6. y <- t(x) %*% x
  7. res <- 1 - y / (sqrt(diag(y)) %*% t(sqrt(diag(y))))
  8. return(res)
  9. }
  10.  
  11. cosineRcpp <- cxxfunction(
  12. signature(Xs = "matrix"),
  13. plugin = c("RcppArmadillo"),
  14. body='
  15. Rcpp::NumericMatrix Xr(Xs); // creates Rcpp matrix from SEXP
  16. int n = Xr.nrow(), k = Xr.ncol();
  17. arma::mat X(Xr.begin(), n, k, false); // reuses memory and avoids extra copy
  18. arma::mat Y = arma::trans(X) * X; // matrix product
  19. arma::mat res = (1 - Y / (arma::sqrt(arma::diagvec(Y)) * arma::trans(arma::sqrt(arma::diagvec(Y)))));
  20. return Rcpp::wrap(res);
  21. ')
  22.  
  23. mat <- matrix(rnorm(100000), ncol=1000)
  24.  
  25. x <- cosine(mat)
  26. y <- cosineRcpp(mat)
  27. identical(x, y)
  28. [1] TRUE
Add Comment
Please, Sign In to add comment