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
}
Add the following code to your website.
For more information on customizing the embed code, read Embedding Snippets.