[Numpy-discussion] Add a function to broadcast arrays to a given shape to numpy's stride_tricks?

Stephan Hoyer shoyer at gmail.com
Sun Dec 7 02:10:46 EST 2014

I recently wrote function to manually broadcast an ndarray to a given shape
according to numpy's broadcasting rules (using strides):

The same functionality can be done pretty straightforwardly with
np.broadcast_arrays, but that function does both too much (I don't actually
have a second array that needs to be broadcast) and not enough (I need to
create a dummy array to broadcast against it).

This approach is simpler, and also, according to my benchmarks, about 3x
faster than np.broadcast_arrays:

In [1]: import xray
In [2]: import numpy as np
In [3]: x = np.random.randn(4)
In [4]: y = np.empty((2, 3, 4))
In [5]: %timeit xray.core.utils.as_shape(x, y.shape)
100000 loops, best of 3: 17 µs per loop
In [6]: %timeit np.broadcast_arrays(x, y)[0]
10000 loops, best of 3: 47.4 µs per loop

Would this be a welcome addition to numpy's lib.stride_tricks? If so, I
will put together a PR.

In my search, I turned up a Stack Overflow post looking for similar

-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/numpy-discussion/attachments/20141206/365fa984/attachment.html>

More information about the NumPy-Discussion mailing list