[Numpy-discussion] computing average distance

Charles R Harris charlesr.harris@gmail....
Mon Nov 3 11:48:47 CST 2008


On Sun, Nov 2, 2008 at 12:23 PM, Paul Rudin <paul@rudin.co.uk> wrote:

>
> I'm experimenting with numpy and I've just written the code below, which
> computes the thing I want (I think). Self.bits is an RxRxR array
> representing a voxelized 3d model - values are either 0 or 1. I can't
> help thinking that's there must be a much nicer way to do it. Any
> suggestions?
>
>
>  centre = numpy.array(scipy.ndimage.measurements.center_of_mass(self.bits))
>
>  vectors = []
>  for x in xrange(R):
>    for y in xrange(R):
>        for z in xrange(R):
>            if self.bits[x,y,z]:
>                vectors.append([x,y,z])
>
>  vectors = numpy.array(vectors)
>  distances = numpy.sqrt(numpy.sum((vectors-centre) ** 2.0, axis=1))
>  av_dist = numpy.average(distances)
>

Try nonzero:

In [5]: bits = np.random.random_integers(0,1, size=(3,3,3))

In [6]: vectors = nonzero(bits)

In [7]: vectors
Out[7]:
(array([0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 2, 2, 2, 2, 2, 2]),
 array([0, 0, 0, 1, 1, 2, 2, 0, 0, 1, 2, 2, 0, 0, 1, 1, 2, 2]),
 array([0, 1, 2, 0, 1, 0, 2, 0, 2, 0, 1, 2, 0, 1, 0, 2, 0, 2]))

The arrays three arrays contain the x, y, z indices.

 Chuck
-------------- next part --------------
An HTML attachment was scrubbed...
URL: http://projects.scipy.org/pipermail/numpy-discussion/attachments/20081103/42345d47/attachment.html 


More information about the Numpy-discussion mailing list