R/distances.R

Defines functions distances

distances <- function(x, y) {
  # retrieve required dimensions
  n <- as.integer(nrow(x))
  k <- as.integer(nrow(y))

  # pre-allocation
  distMatrix <- matrix(data = 0, nrow = n, ncol = k)

  # fill the distance matrix, dimensions: n x k, where n is the number of
  # observations and k the number of points to which the distance is measured,
  # the element with indices [2,3] gives the squared Euclidean distances between
  # the second observation and the third centroid

  for (i in 1:k) {
    distMatrix[, i] <- rowSums(t(t(x) - y[i, ])^2)
  }

  distMatrix
}
heiligerl/kMeans_Rpackage documentation built on Aug. 16, 2020, 4:04 p.m.