[Numpy-discussion] repmat equivalent?
Albert Strasheim
fullung at gmail.com
Thu Feb 23 03:32:03 CST 2006
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
loops.
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)
produces:
[[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
dimensions.
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.
Regards
Albert
More information about the Numpy-discussion
mailing list