I am trying to write code (using R) that returns a matrix that contains the squared distance between all pairs of rows. Below is an implementation that I have written. It works as expected but can get very slow as the number of rows gets large. From my observations this line (combn(x,m=2)) takes the longest to run. Hence I was wondering if anyone has any suggestions as to how the code can be made more efficient for large number of rows.Thanks in advance
gen.dist <- function(x){
n <- nrow(x)
idx <- combn(seq(1,n),m=2)
d <- apply(x, 2, calc.distance, combinations=idx,alpha=2)
return(list(n=n,d=d))
}
calc.distance <- function(x,combinations,alpha){
x1 <- x[combinations[1,]]
x2 <- x[combinations[2,]]
output <- (x1 - x2)^alpha
return(output)
}