Skip to content
Back to formatted view

Raw Message

Message-ID: <31a7f73a0911201405v7d446e53qf5a7364804739216@mail.gmail.com>
Date: 2009-11-20T22:05:24Z
From: Andrew Barr
Subject: help me avoid nested for() loops!

Hi R folks,

I have a massive array (object name "points") in the following form

     [,1]     [,2]
[1,] 1369   22
[2,] 1370   22
[3,] 1368   23
[4,] 1369   23
[5,] 1370   23
[6,] 1371   23
(10080 rows truncated)

These represent pixel coordinates of interest in a jpeg image.  I need
to find the distance from each point to all other points of interest.
The only way I can see to do this is by pythagoras and nested for
loops.

distance<-function(x1,y1,x2,y2){sqrt((x2-x1)^2 + (y2-y1)^2)} #pythagoras
for(i in 1:nrow(points)){
	for(j in 1:nrow(points)){
	dist<-c(dist,distance(points[i,1],point.array.indices[i,2],points[j,1],points[j,2]))
}
}

This is obviously prohibitively slow with >10000 rows in the array.

Any thoughts on how to do this without for loops? I apologize in
advance if there is an obvious way around this.

Thanks!

Andrew Barr
University of Texas at Austin