Skip to content
Prev 164173 / 398506 Next

Need help optimizing/vectorizing nested loops

On Tue, 9 Dec 2008, tyler wrote:

            
Cast the neighborhoods as an indicator matrix, then use matrix 
multiplications:
user  system elapsed
    1.18    0.00    1.20
+ mn <- with(dat,outer(1:25,1:25, function(i,j) abs(X[i]-X[j])<2 & abs(Y[i]-Y[j])<2 & i!=j ))
+ print(all.equal(rowSums(mn%*%as.matrix(dat[,-(1:2)])>0),tmp))})
[1] TRUE
    user  system elapsed
       0       0       0


HTH,

Chuck
Charles C. Berry                            (858) 534-2098
                                             Dept of Family/Preventive Medicine
E mailto:cberry at tajo.ucsd.edu	            UC San Diego
http://famprevmed.ucsd.edu/faculty/cberry/  La Jolla, San Diego 92093-0901