[Numpy-discussion] numpy-izing a loop
Paul Rudin
paul@rudin.co...
Wed Feb 11 02:25:40 CST 2009
Stéfan van der Walt <stefan@sun.ac.za> writes:
> 2009/2/10 Stéfan van der Walt <stefan@sun.ac.za>:
>> x = np.arange(dim)
>> y = np.arange(dim)[:, None]
>> z = np.arange(dim)[:, None, None]
>
> Do not operate heavy machinery or attempt broadcasting while tired or
> under the influence. That order was incorrect:
>
>> z = np.arange(dim)
>> y = np.arange(dim)[:, None]
>> x = np.arange(dim)[:, None, None]
Thanks to you both. I can confirm that the two functions below give the
same result - as far as my comprehensive testing of one example shows :)
def compute_voxels(depth_buffers):
assert len(depth_buffers) == 6
dim = depth_buffers[0].shape[0]
znear, zfar, ynear, yfar, xnear, xfar = depth_buffers
result = numpy.empty((dim, dim, dim), numpy.bool)
for x in xrange(dim):
for y in xrange(dim):
for z in xrange(dim):
result[x, y, z] = ((xnear[y, z] < xfar[y, z]) and
(ynear[x, z] < yfar[x, z]) and
(znear[x, y] < zfar[x, y]))
return result
def compute_voxels2(depth_buffers):
dim = depth_buffers[0].shape[0]
znear, zfar, ynear, yfar, xnear, xfar = depth_buffers
z = numpy.arange(dim)
y = numpy.arange(dim)[:, None]
x = numpy.arange(dim)[:, None, None]
return ((xnear[y,z] < xfar[y, z]) &
(ynear[x, z] < yfar[x, z]) &
(znear[x,y] < zfar[x,y]))
All that remains is for me to verify that it's actually the result I want :)
(Well - I also need to learn to spot these things for myself, but I
guess the intuition comes with practice.)
More information about the Numpy-discussion
mailing list