# [SciPy-user] Avoiding For Loops Question

Joseph Smidt josephsmidt@gmail....
Fri Jun 5 12:03:46 CDT 2009

```Hey, thanks a lot, you guys are the best.

On Fri, Jun 5, 2009 at 9:37 AM, Whitcomb, Mr.
Tim<tim.whitcomb@nrlmry.navy.mil> wrote:
>>    Now, is it possible to write get around these types of for
>> loops using any tools from scipy?
>
> Numpy, yes.
>
>> for i in xrange(len(x)):
>>      a[i] = i*(i+1)/2*x[i]
>>
>
> The values of i are just indices, and those can be precomputed
> beforehand:
> i = numpy.arange(len(x))
> a[:] = i[:]*(i[:]+1)/2*x[:]
>
>> for i in xrange(y.shape[0]):
>>     for k in xrange(y.shape[1]):
>>         a[i] += x[i] + y[i][k]
>
> Break the sum into two pieces - the x component is just repeated
> y.shape[1] times, and y is added up along the second axis:
> a[:] = x[:]*y.shape[1] + y[:].sum(axis=1)
>
>> for i in xrange(y.shape[0]):
>>     for k in xrange(y.shape[1]):
>>         a[i][k] = x[i] + y[i][k]
>
> Here, you are copying y into a, then adding the same value of x across
> an entire axis.  Use array broadcasting to make x be the same shape as
> y, but with each column the same value:
> a[:,:] = x[:, numpy.newaxis] + y[:,:]
>
> I don't know what the style standard is regarding using the colons to
> indicate entire arrays (i.e.
> a = x[:,numpy.newaxis] + y instead), but these should work for you.
>
> Tim
>
>
> _______________________________________________
> SciPy-user mailing list
> SciPy-user@scipy.org
> http://mail.scipy.org/mailman/listinfo/scipy-user
>

--
------------------------------------------------------------------------
Joseph Smidt <josephsmidt@gmail.com>

Physics and Astronomy
4129 Frederick Reines Hall
Irvine, CA 92697-4575
Office: 949-824-3269
```