views:

378

answers:

4

I found repmat([1;1], [1 1 1]) in MATLAB code.

I am trying to find a NumPy command to do the same thing, but I found that can't use with 3d [1 1 1] ?

+4  A: 

See NumPy for Matlab users.

Matlab:

repmat(a, 2, 3)

Numpy:

numpy.kron(numpy.ones((2,3)), a)
rcs
I don't think the mathesaurus link is very good. There is an Numpy For Matlab Users page as part of the official documentation which is more comprehensive and up to date: http://www.scipy.org/NumPy_for_Matlab_Users
thrope
thank you, rcs ,i will try it
vernomcrp
+5  A: 

Note that some of the reasons you'd need to use MATLAB's repmat are taken care of by NumPy's broadcasting mechanism, which allows you to do various types of math with arrays of similar shape. So if you had, say, a 1600x1400x3 array representing a 3-color image, you could (elementwise) multiply it by [1.0 0.25 0.25] to reduce the amount of green and blue at each pixel. See the above link for more information.

kwatford
thank kwatford :)
vernomcrp
+3  A: 

Here is a much better (official) NumPy for Matlab Users link - I'm afraid the mathesaurus one is quite out of date.

The numpy equivalent of repmat(a, m, n) is tile(a, (m, n)).

This works with multiple dimensions and gives a similar result to matlab. (Numpy gives a 3d output array as you would expect - matlab for some reason gives 2d output - but the content is the same).

Matlab:

>> repmat([1;1],[1,1,1])

ans =
     1
     1

Python:

In [46]: a = np.array([[1],[1]])
In [47]: np.tile(a, [1,1,1])
Out[47]: 
array([[[1],
        [1]]])
thrope
when i try size(repmat([1;1],[1,1,2])) it get ans = 2 1 2 [in matlab] but in python np.tile(a,[1,1,2]).shape it get(1, 2, 2) , i want numpy give result as same as matlab
vernomcrp
np.tile(a[:,np.newaxis],[1,1,2]) - it gives the same. Problem is tile promotes `a` to the dimension of the tile argument by *prepending* new axes as necessary. Matlab seems to work the other way. Similarly, with 4d tiling you will need newaxis twice... so `np.tile(a[:,newaxis,newaxis],[1,2,3,4]) = size(repmat(a,[1 2 3 4]))` as required...
thrope
A: 

Know both tile and repeat.

x = numpy.arange(5)
print numpy.tile(x, 2)
print x.repeat(2)
Steve