Skip to content

Instantly share code, notes, and snippets.

@mpjdem
Last active September 23, 2019 11:53
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save mpjdem/26a9f7473ef256fdc866ef7116e85b47 to your computer and use it in GitHub Desktop.
Save mpjdem/26a9f7473ef256fdc866ef7116e85b47 to your computer and use it in GitHub Desktop.
All pairwise Euclidean distances between two matrices in R, using Rcpp
library(Rcpp)
cppFunction('NumericMatrix crossdist(NumericMatrix m1, NumericMatrix m2) {
int nrow1 = m1.nrow();
int nrow2 = m2.nrow();
int ncol = m1.ncol();
if (ncol != m2.ncol()) {
throw std::runtime_error("Incompatible number of dimensions");
}
NumericMatrix out(nrow1, nrow2);
for (int r1 = 0; r1 < nrow1; r1++) {
for (int r2 = 0; r2 < nrow2; r2++) {
double total = 0;
for (int c12 = 0; c12 < ncol; c12++) {
total += pow(m1(r1, c12) - m2(r2, c12), 2);
}
out(r1,r2) = sqrt(total);
}
}
return out;
}')
res <- crossdist(matrix(runif(3000), ncol = 3),
matrix(runif(600), ncol = 3))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment