[Numpy-discussion] how do I speed up this?

Timothy Hochberg tim.hochberg@ieee....
Tue Nov 27 13:26:30 CST 2007


On Nov 27, 2007 11:38 AM, Giorgio F. Gilestro <giorgio@gilestro.tk> wrote:

> Hello everyone,
>
> ma and new_ma are bi-dimensional array with shape (a1, a2) on which I am
> performing the following iteration:
>
> for fd in range(a1):
>     new_ma[fd] = [( ma[fd][i-5:i+5].sum() == 0 )*1 for i in range (a2)]


This looks like it's probably buggy; when, for example,, a2 == 0, I don't
think ma[fd][-5:5] is going to return what you want.

>
> Is there any faster more elegant way to do that with numpy?


There are faster ways, I'm not sure that they are more elegant. It looks
like what you want is essentially a moving average, possible with periodic
boundary conditions. There are a few different tricks that can make this
fast; which is appropriate depends on what the shape of ma is expected to
be. If 'a1' if large, then you can profitably remove the outer loop;
something vaguely like:

for i in range(a2):
    new_ma[:, i] = ( ma[fd][i-5:i+5].sum() == 0)

(This is still buggy as above, since I'm not sure what kind of boundary
conditions you need).

If that's not applicable, another approach is to loop over the offset, in
this case -5 to 5, and remove the loop over a2. That method is more
complicated and I'm going to avoid describing it in detail unless needed.
One might even be able to do both, but that's probably overkill.

HTH

-- 
.  __
.   |-\
.
.  tim.hochberg@ieee.org
-------------- next part --------------
An HTML attachment was scrubbed...
URL: http://projects.scipy.org/pipermail/numpy-discussion/attachments/20071127/a1a81dc0/attachment.html 


More information about the Numpy-discussion mailing list