[SciPy-user] Avoiding For Loops Question

Whitcomb, Mr. Tim tim.whitcomb@nrlmry.navy....
Fri Jun 5 11:37:22 CDT 2009

>    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
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.


More information about the SciPy-user mailing list