Skip to content

nearest distance in matrix

1 message · Barry Rowlingson

#
Marius Gilbert wrote:
Try this, which uses an internal, undocumented Spatstat function 
'exactPdt':

library(spatstat)
nmatdist <- function(aMat){
   storage.mode(aMat) <- "logical"
   win <- owin(xrange=c(1,ncol(aMat)),yrange=c(1,nrow(aMat)),mask=aMat)
   m <- exactPdt(win)
   return(m$d)
}
test:

 > m1
      [,1] [,2] [,3] [,4] [,5]
[1,]    0    0    0    0    0
[2,]    1    0    0    0    0
[3,]    1    1    0    0    0
[4,]    0    0    0    0    0
 > nmatdist(m1)
      [,1]     [,2]     [,3]     [,4]     [,5]
[1,]    1 1.414214 2.236068 2.828427 3.605551
[2,]    0 1.000000 1.414214 2.236068 3.162278
[3,]    0 0.000000 1.000000 2.000000 3.000000
[4,]    1 1.000000 1.414214 2.236068 3.162278

  looks about right!

Baz