Skip to content

nearest distance in matrix

4 messages · White.Denis@epamail.epa.gov, Barry Rowlingson, Marius Gilbert

#
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))
}

Denis White
   US EPA, 200 SW 35th St, Corvallis, Oregon, 97333 USA
   voice: 541.754.4476, email: white.denis at epa.gov
   web: www.epa.gov/wed/pages/staff/white/

r-sig-geo-bounces at stat.math.ethz.ch wrote on 2004-07-14 09:50:16:
with
0)
cell
#
White.Denis at epamail.epa.gov wrote:
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
#
Yup.  Space complexity is O((nrow(mat)*ncol(mat))^2).


r-sig-geo-bounces at stat.math.ethz.ch wrote on 2004-07-14 10:49:14:
rows
my
matrix
#
Dear Barry,
I knew there should be way to do it without estimating the full distance 
redistribution matrix O((nrow(mat)*ncol(mat))^2) because the equivalent  
AV Spatial analyst can do rather big raster (3000 x 3000 pixels) in a few 
seconds.
It is super quick indeed, I tested it on a 1600 x 250 matrix, ang got the 
output 1600x250 distance matrix in less than 5 seconds on a PIV 1700 Mhz, 
so fairly efficient indeed,

Many thanks, there's no I could have found this myself,

Cheers,

Marius