[Numpy-discussion] repmat equivalent?

Travis Oliphant oliphant.travis at ieee.org
Thu Feb 23 12:34:02 CST 2006

```Albert Strasheim wrote:

>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.
>
>
There is a function in scipy.linalg called kron that could be brought
over which can do a repmat.

In file: /usr/lib/python2.4/site-packages/scipy/linalg/basic.py

def kron(a,b):
"""kronecker product of a and b

Kronecker product of two matrices is block matrix
[[ a[ 0 ,0]*b, a[ 0 ,1]*b, ... , a[ 0 ,n-1]*b  ],
[ ...                                   ...   ],
[ a[m-1,0]*b, a[m-1,1]*b, ... , a[m-1,n-1]*b  ]]
"""
if not a.flags['CONTIGUOUS']:
a = reshape(a, a.shape)
if not b.flags['CONTIGUOUS']:
b = reshape(b, b.shape)
o = outerproduct(a,b)
o=o.reshape(a.shape + b.shape)
return concatenate(concatenate(o, axis=1), axis=1)

Thus,

kron(ones((2,3)), arr)

>>> sl.kron(ones((2,3)),arr)
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]])

gives you the equivalent of

repmat(arr, 2,3)

We could bring this over from scipy into numpy as it is simple enough.

It has a multidimensional extension (i.e. you can pass in a and b as
higher dimensional arrays),  But, don't ask me to explain it to you
because I can't without further study....

-Travis

```