# [Numpy-tickets] [NumPy] #292: Make repmat work for arbitrary dimensions

NumPy numpy-tickets at scipy.net
Sat Sep 23 11:12:21 CDT 2006

```#292: Make repmat work for arbitrary dimensions
-------------------------+--------------------------------------------------
Reporter:  baxissimo    |       Owner:  somebody
Type:  enhancement  |      Status:  new
Priority:  normal       |   Milestone:
Component:  numpy.lib    |     Version:
Severity:  normal       |    Keywords:
-------------------------+--------------------------------------------------
repmat() should work with inputs of any shape and take a tuple for the
output number of repeats.

If this is considered too big a change to replace repmat's 3-argument
signature with an incompatible 2-arg one, then a new function 'reparray'

An example implementation is below
{{{
def reparray(A, tup):
"""Repeat an array the number of times given in the integer tuple,
tup.

Similar to repmat, but works for arrays of any dimension.
reparray(A,(m,n)) is equivalent to repmat(A,m,n)

If tup has length d, the result will have dimension of max(d, A.ndim).
If tup is scalar it is treated as a 1-tuple.

If A.ndim < d, A is promoted to be d-dimensional by prepending new
axes.
So a shape (3,) array is promoted to (1,3) for 2-D replication,
or shape (1,1,3) for 3-D replication.
If this is not the desired behavior, promote A to d-dimensions
manually
before calling this function.

If d < A.ndim, tup is promoted to A.ndim by appending 1's to it.  Thus
for an A.shape of (2,3,4,5), a tup of (2,2) is treated as (2,2,1,1)

Examples:
>>> a = array([0,1,2])
>>> reparray(a,2)
array([0, 1, 2, 0, 1, 2])
>>> reparray(a,(1,2))
array([[0, 1, 2, 0, 1, 2]])
>>> reparray(a,(2,2))
array([[0, 1, 2, 0, 1, 2],
[0, 1, 2, 0, 1, 2]])
>>> reparray(a,(2,1,2))
array([[[0, 1, 2, 0, 1, 2]],

[[0, 1, 2, 0, 1, 2]]])

repmat, repeat
"""
if numpy.isscalar(tup):
tup = (tup,)
d = len(tup)
c = numpy.array(A,copy=False,subok=True,ndmin=d)
shape = list(c.shape)
n = c.size
for i, nrep in enumerate(tup):
if nrep!=1:
c = c.reshape(-1,n).repeat(nrep,0)
dim_in = shape[i]
dim_out = dim_in*nrep
shape[i] = dim_out
n /= dim_in
return c.reshape(shape)
}}}
A more complete version with two implementations and tests and timing code
is attached.

--
Ticket URL: <http://projects.scipy.org/scipy/numpy/ticket/292>
NumPy <http://projects.scipy.org/scipy/numpy>
The fundamental package needed for scientific computing with Python.
```