[Numpy-discussion] computing average distance

Emmanuelle Gouillart emmanuelle.gouillart@normalesup....
Sun Nov 2 13:39:39 CST 2008


Hello Paul,

although I'm not an expert either, it seems to me you could improve your
code a lot by using numpy.mgrid 
Below is a short example of what you could do
coordinates = numpy.mgrid[0:R, 0:R, 0:R]
X, Y, Z = coordinates[0].ravel(), coordinates[1].ravel(),coordinates[2].ravel() bits = self.bits.ravel() 
distances = numpy.sqrt((X[bits==1]-centre[0])**2 +
	(Y[bits==1]-centre[0])**2 + (Z[bits==1]-centre[0])**2)

There must be a way to do it without flattening the arrays, but I haven't
found it. Anyway, you can surely do what you want without a loop!

Cheers,

Emmanuelle

On Sun, Nov 02, 2008 at 07:23:06PM +0000, Paul Rudin 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)


> _______________________________________________
> Numpy-discussion mailing list
> Numpy-discussion@scipy.org
> http://projects.scipy.org/mailman/listinfo/numpy-discussion


More information about the Numpy-discussion mailing list