# [Numpy-discussion] repeat an array without allocation

Jaime Fernández del Río jaime.frio at gmail.com
Mon May 5 02:20:25 EDT 2014

```On Sun, May 4, 2014 at 9:34 PM, srean <srean.list at gmail.com> wrote:

> Hi all,
>
>   is there an efficient way to do the following without allocating A where
>
>  A = np.repeat(x, [4, 2, 1, 3], axis=0)
>  c = A.dot(b)    # b.shape
>

If x is a 2D array you can call repeat **after** dot, not before, which
will save you some memory and a few operations:

>>> a = np.random.rand(4, 5)
>>> b = np.random.rand(5, 6)
>>> np.allclose(np.repeat(a, [4, 2, 1, 3], axis=0).dot(b),
...             np.repeat(a.dot(b), [4, 2, 1, 3], axis=0))
True

Similarly, if x is a 1D array, you can sum the corresponding items of b
before calling dot:

>>> a = np.random.rand(4)
>>> b = np.random.rand(10)
>>> idx = np.concatenate(([0], np.cumsum([4,2,1,3])[:-1]))
>>> np.allclose(np.dot(np.repeat(a, [4,2,1,3] ,axis=0), b),
... )
True

Jaime

--
(\__/)
( O.o)
( > <) Este es Conejo. Copia a Conejo en tu firma y ayúdale en sus planes
de dominación mundial.
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/numpy-discussion/attachments/20140504/60246369/attachment.html>
```