R/InterpointMat.r

#' This function calculates the interpoint distance between two matrices. 
#' 
#' @param X A matrix, with each row represents one data object, and the number of columns represents the number of features.
#' @param Y A matrix, with each row represents one data object, and the number of columns represents the number of features.
#' @return The interpoint distances between two matrices. 
#' @examples
#' X = matrix(c(1,2,3,4), ncol = 2)
#' Y = matrix(c(5,6,7,8), ncol = 2)
#' InterpointMat(X, Y)
InterpointMat = function (X, Y) {
  
  # number of columns in X
  p = ncol(X)
  
  # number of rows of X and Y
  nx <- nrow(X)
  ny <- nrow(Y)
  
  # the length of each data object in X and Y squared
  norm2.x <- apply(X^2, 1, sum)
  norm2.y <- apply(Y^2, 1, sum)
  
  # calculates the interpoint distance
  dist <- sqrt(matrix(norm2.x, nrow = nx, ncol = ny) + matrix(norm2.y, nrow = nx, ncol = ny, byrow = T) - 2*X%*%t(Y))
  
  return(dist)
  
}
hankuipeng/HKCluster documentation built on May 27, 2019, 8:45 a.m.