From: Albert S. <fu...@gm...> - 2006-02-23 11:31:53
|
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 =3D=3D 1: a =3D array([a]) (origrows, origcols) =3D a.shape rows =3D origrows * m cols =3D origcols * n b =3D 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 so= lve: - 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 =3D repmat(1, 1, 1) assert_equal(a, 1) a =3D repmat(array([1]), 1, 1) assert_array_equal(a, array([1])) a =3D repmat(array([1,2]), 2, 3) assert_array_equal(a, array([[1,2,1,2,1,2], [1,2,1,2,1,2]])) a =3D 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 |