<div dir="ltr"><div class="gmail_extra"><div class="gmail_quote">2015-02-13 13:25 GMT+01:00 Julian Taylor <span dir="ltr"><<a href="mailto:jtaylor.debian@googlemail.com" target="_blank">jtaylor.debian@googlemail.com</a>></span>:<br><blockquote class="gmail_quote" style="margin:0 0 0 .8ex;border-left:1px #ccc solid;padding-left:1ex"><span class="">On 02/13/2015 01:03 PM, Francesc Alted wrote:<br>
> 2015-02-13 12:51 GMT+01:00 Julian Taylor <<a href="mailto:jtaylor.debian@googlemail.com">jtaylor.debian@googlemail.com</a><br>
</span>> <mailto:<a href="mailto:jtaylor.debian@googlemail.com">jtaylor.debian@googlemail.com</a>>>:<br>
<div><div class="h5">><br>
> On 02/13/2015 11:51 AM, Francesc Alted wrote:<br>
> > Hi,<br>
> ><br>
> > I would like to vectorize the next computation:<br>
> ><br>
> > nx, ny, nz = 720, 180, 3<br>
> > outheight = np.arange(nz) * 3<br>
> > oro = np.arange(nx * ny).reshape((nx, ny))<br>
> ><br>
> > def compute1(outheight, oro):<br>
> > result = np.zeros((nx, ny, nz))<br>
> > for ix in range(nx):<br>
> > for iz in range(nz):<br>
> > result[ix, :, iz] = outheight[iz] + oro[ix, :]<br>
> > return result<br>
> ><br>
> > I think this should be possible by using an advanced use of<br>
> broadcasting<br>
> > in numpy. Anyone willing to post a solution?<br>
><br>
><br>
> result = outheight + oro.reshape(nx, ny, 1)<br>
><br>
><br>
> And 4x faster for my case. Oh my, I am afraid that my mind will never<br>
> scratch all the amazing possibilities that broadcasting is offering :)<br>
><br>
> Thank you very much for such an elegant solution!<br>
><br>
<br>
<br>
</div></div>if speed is a concern this is faster as it has a better data layout for<br>
numpy during the computation, but the result may be worse layed out for<br>
further processing<br>
<br>
result = outheight.reshape(nz, 1, 1) + oro<br>
return np.rollaxis(result, 0, 3)<br>
<div class="HOEnZb"><div class="h5"><br></div></div></blockquote><div><br></div><div>Holly cow, this makes for another 4x speed improvement! I don't think I need that much in my scenario, so I will stick with the first one (more readable and the expected data layout), but thanks a lot!</div><div><br></div><div>Francesc</div></div>
</div></div>