[Numpy-discussion] general version of repmat?

Bill Baxter wbaxter at gmail.com
Fri Sep 22 08:31:26 CDT 2006


Ok, here's my best shot at a generalized repmat:

def reparray(A, tup):
    if numpy.isscalar(tup):
        tup = (tup,)
    d = len(tup)
    A = numpy.array(A,copy=False,subok=True,ndmin=d)
    for i,k in enumerate(tup):
        A = numpy.concatenate([A]*k, axis=i)
    return A


Can anyone improve on this?  The only way I could think to seriously
improve it would be if there were an N-way concatenate() function in
the C-API.  Each call to concatenate() involves a potentially big
allocation and memcpy of the data.


And here's a docstring for it:
    """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, ndim is effectively promoted to A.ndim by appending 1's
    to tup.


    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]]])

    See Also:
       repmat, repeat
    """




More information about the Numpy-discussion mailing list