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="") ______________________________________________ R-help@r-project.org mailing list https://stat.ethz.ch/mailman/listinfo/r-help PLEASE do read the posting guide http://www.R-project.org/posting-guide.html and provide commented, minimal, self-contained, reproducible code.