[Numpy-discussion] repmat equivalent?

Nadav Horesh nadavh at visionsense.com
Thu Feb 23 04:12:06 CST 2006

You should really use the "repeat" function.


-----Original Message-----
From:	numpy-discussion-admin at lists.sourceforge.net on behalf of Albert Strasheim
Sent:	Thu 23-Feb-06 13:31
To:	numpy-discussion at lists.sourceforge.net
Subject:	[Numpy-discussion] repmat equivalent?
Hello all

I recently started using NumPy and one function that I am really
missing from MATLAB/Octave is repmat. This function is very useful for
implementing algorithms as matrix multiplications instead of for

Here's my first attempt at repmat for 1d and 2d (with some
optimization by Stefan van der Walt):

def repmat(a, m, n):
    if a.ndim == 1:
        a = array([a])
    (origrows, origcols) = a.shape
    rows = origrows * m
    cols = origcols * n
    b = a.reshape(1,a.size).repeat(m, 0).reshape(rows, origcols).repeat(n, 0)
    return b.reshape(rows, cols)

print repmat(array([[1,2],[3,4]]), 2, 3)


[[1 2 1 2 1 2]
 [3 4 3 4 3 4]
 [1 2 1 2 1 2]
 [3 4 3 4 3 4]]

which is the same as in MATLAB.

There are various issues with my function that I don't quite know how to solve:

- How to handle scalar inputs (probably need asarray here)
- How to handle more than 2 dimensions

More than 2 dimensions is tricky, since NumPy and MATLAB don't seem to
agree on how more-dimensional data is organised? As such, I don't know
what a NumPy user would expect repmat to do with more than 2

Here are some test cases that the current repmat should pass, but doesn't:

a = repmat(1, 1, 1)
assert_equal(a, 1)
a = repmat(array([1]), 1, 1)
assert_array_equal(a, array([1]))
a = repmat(array([1,2]), 2, 3)
assert_array_equal(a, array([[1,2,1,2,1,2], [1,2,1,2,1,2]]))
a = repmat(array([[1,2],[3,4]]), 2, 3)
assert_array_equal(a, array([[1,2,1,2,1,2], [3,4,3,4,3,4],
[1,2,1,2,1,2], [3,4,3,4,3,4]]))

Any suggestions on how do repmat in NumPy would be appreciated.



This SF.Net email is sponsored by xPML, a groundbreaking scripting language
that extends applications into web and mobile media. Attend the live webcast
and join the prime developer group breaking into this new coding territory!
Numpy-discussion mailing list
Numpy-discussion at lists.sourceforge.net

More information about the Numpy-discussion mailing list