Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- require(inline)
- require(RcppArmadillo)
- ## extract cosine similarity between columns
- cosine <- function(x) {
- y <- t(x) %*% x
- res <- 1 - y / (sqrt(diag(y)) %*% t(sqrt(diag(y))))
- return(res)
- }
- cosineRcpp <- cxxfunction(
- signature(Xs = "matrix"),
- plugin = c("RcppArmadillo"),
- body='
- Rcpp::NumericMatrix Xr(Xs); // creates Rcpp matrix from SEXP
- int n = Xr.nrow(), k = Xr.ncol();
- arma::mat X(Xr.begin(), n, k, false); // reuses memory and avoids extra copy
- arma::mat Y = arma::trans(X) * X; // matrix product
- arma::mat res = (1 - Y / (arma::sqrt(arma::diagvec(Y)) * arma::trans(arma::sqrt(arma::diagvec(Y)))));
- return Rcpp::wrap(res);
- ')
- mat <- matrix(rnorm(100000), ncol=1000)
- x <- cosine(mat)
- y <- cosineRcpp(mat)
- identical(x, y)
- [1] TRUE
Add Comment
Please, Sign In to add comment