[SciPy-user] Avoiding For Loops Question

josef.pktd at gmail.com josef.pktd at gmail.com
Fri Jun 5 13:26:50 EDT 2009


On Fri, Jun 5, 2009 at 12:37 PM, Whitcomb, Mr. Tim
<tim.whitcomb at 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.

these 2 are two different operations

 a[:,:] = x[:, numpy.newaxis] + y[:,:]

on right side:  y[:,:] is the same as y, [:,:] is redundant
on the left side a[:,:] =    assigns the content of the right side to
existing array `a`
      if the dimensions don't agree, then you get an exception

a = x[:,numpy.newaxis] + y
this assigns the temporary result of the right side to the name `a`,
no matter what `a` was before

so, in the examples above, I think, you can drop all [:], [:,:]

Josef


>
> Tim



More information about the SciPy-User mailing list