Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the equivalent of MATLAB's repmat in NumPy

I would like to execute the equivalent of the following MATLAB code using NumPy: repmat([1; 1], [1 1 1]). How would I accomplish this?

like image 968
vernomcrp Avatar asked Nov 12 '09 12:11

vernomcrp


People also ask

What is Repmat in Python?

repmat(a, m, n)[source] Repeat a 0-D to 2-D array or matrix MxN times. Parameters aarray_like. The array or matrix to be repeated.

What is the equivalent of Matlab in Python?

NumPy (Numerical Python)NumPy arrays are the equivalent to the basic array data structure in MATLAB. With NumPy arrays, you can do things like inner and outer products, transposition, and element-wise operations.

What is Repmat?

Repmat in Matlab is one of the commands in Matlab which is used for array manipulations. This command gives output in the form of an array repetition of the original array. Here array is a collection of the number of elements, data, information, etc. An array is represented within square brackets in Matlab.

Is NumPy inspired by Matlab?

MATLAB® and NumPy have a lot in common, but NumPy was created to work with Python, not to be a MATLAB clone.


2 Answers

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]]]) 
like image 187
robince Avatar answered Oct 18 '22 05:10

robince


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.

like image 44
kwatford Avatar answered Oct 18 '22 05:10

kwatford