# [Numpy-discussion] How to get rid of the loop?

Anne Archibald peridot.faceted@gmail....
Sat Nov 7 13:33:12 CST 2009

```2009/11/7 Stas K <stanconn@gmail.com>:
> Thank you, Josef
> It is exactly what I want:
>
> ar[:,None]**2 + ar**2
>
> Do you know something about performance of this? In my real program ar  have
> ~ 10k elements, and expression for v more complicated (it has some
> trigonometric functions)

The construction of ar[:,None] (which I prefer to spell
ar[:,np.newaxis]) is cheap, since it just constructs a "view" into ar.
Computing ar**2 and ar[:,None] require squaring each element of ar,
but this is done in a C loop. (It's done twice in this expression, so
this isn't as efficient as it might be). Only when it comes time to do
the addition do you do n**2 operations. For very large n, this can be
a crushing memory burden, and if you only need these values for an
intermediate calculation it sometimes turns out that it's better to
loop over one of the dimensions. But this expression is probably about
as efficient as you can hope for, given what it does. If you need to
do some more complicated calculation, the main thing to be careful of
is that you do as much calculation as possible on the separate arrays,
while they're still only n elements and not n**2.

Anne

> On 07.11.2009, at 21:57, josef.pktd@gmail.com wrote:
>
> On Sat, Nov 7, 2009 at 1:51 PM, Stas K <stanconn@gmail.com> wrote:
>
> Can I get rid of the loop in this example? And what is the fastest way
>
> to get v in the example?
>
> ar = array([1,2,3])
>
> for a in ar:
>
>    for b in ar:
>
>        v = a**2+b**2
>
> ar[:,None]**2 + ar**2
>
> array([[ 2,  5, 10],
>       [ 5,  8, 13],
>       [10, 13, 18]])
>
> I think, for this case there is also directly a function in numpy
> hypot which should also work.
>
> Josef
>
> _______________________________________________
>
> NumPy-Discussion mailing list
>
> NumPy-Discussion@scipy.org
>
> http://mail.scipy.org/mailman/listinfo/numpy-discussion
>
> _______________________________________________
> NumPy-Discussion mailing list
> NumPy-Discussion@scipy.org
> http://mail.scipy.org/mailman/listinfo/numpy-discussion
>
>
> _______________________________________________
> NumPy-Discussion mailing list
> NumPy-Discussion@scipy.org
> http://mail.scipy.org/mailman/listinfo/numpy-discussion
>
>
```