Skip to content

Instantly share code, notes, and snippets.

@bobthecat
Created June 9, 2012 23:29
Show Gist options
  • Save bobthecat/2903031 to your computer and use it in GitHub Desktop.
Save bobthecat/2903031 to your computer and use it in GitHub Desktop.
Rcpp cosine similarity
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
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment