更有效的方法来计算R中的平方距离

时间:2016-10-21 04:05:02

标签: r performance time distance-matrix

我正在尝试编写代码(使用R),该代码返回一个矩阵,其中包含所有行对之间的平方距离。以下是我编写的实现。它按预期工作,但随着行数变大,速度会变慢。根据我的观察,这条线(combn(x,m = 2))运行时间最长。因此,我想知道是否有人有任何关于如何使代码对大量行更有效的建议。谢谢提前

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)
}

0 个答案:

没有答案
相关问题