[R-sig-Geo] nearest distance in matrix

Barry Rowlingson B.Rowlingson at lancaster.ac.uk
Wed Jul 14 19:49:14 CEST 2004


White.Denis at epamail.epa.gov wrote:
> 
> 
> 
> Here's another version that probably can be simplified:
> 
> nmatdist <- function (m)
> {
>     v <- as.vector (m)
>     ind <- as.matrix (expand.grid (seq (nrow (m)), seq (ncol (m))))
>     d <- as.matrix (dist (ind, upper=TRUE))
>     ones <- as.numeric (dimnames(ind[v == 1,])[[1]])
>     matrix (sapply (seq(nrow(ind)),
>         function (x) min (d[x, ones])), nrow=nrow(m))
> }

  Eeek! Have you tried that on a 100x100 matrix? Darn near killed my 
machine!

  > mt=matrix(runif(10000)>.1,100,100)
  > nmatdist(mt)
   ... near swap death experience...

  The code used by Adrian Baddeley's spatstat routine uses a very neat 
method for working out the distances, which involves sweeping along rows 
and columns or something. He did explain it to me when I was in Perth 
but I can't recall it now!

  Anyway, its super-quick and uses next-to-no memory. Here's how long my 
function that calls the spatstat routine takes:

  > unix.time(nmatdist(mt))
  [1] 0.02 0.01 0.02 0.00 0.00

  it was so quick I thought I'd check I'd not done it on a small matrix 
by mistake:

  > dim(mt)
  [1] 100 100

Nope!

Baz




More information about the R-sig-Geo mailing list