[R] speeding up "sum of squared differences" calculation

Bos, Roger roger.bos at rothschild.com
Mon Oct 21 22:30:08 CEST 2013


All,

I am using a sum of squared differences in the objective function of an optimization problem I am doing and I have managed to speed it up using the outer function versus the nested for loops, but my suspicion is that the calculation could be done even quicker.  Please see the code below for a simple example.  If anyone can point out a faster way I would appreciate it greatly.

Thanks,

Roger

X <- runif(1000)

now <- proc.time()
ans <- 0
for (i in 1:length(X)) {
  for (j in 1:length(X)) {
    ans <- ans + (X[i]-X[j])*(X[i]-X[j])
  }
}
ans
speed <- proc.time() - now; cat(" That took ", round(speed[3],1), " secs.\n", sep="")

now <- proc.time()
gg <- outer(X, X, FUN="-")
sum(gg*gg)
speed <- proc.time() - now; cat(" That took ", round(speed[3],1), " secs.\n", sep="")



More information about the R-help mailing list