Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Repeat each element of a matrix in as a block into a new matrix [duplicate]

In Matlab, there is the command repelem which works as follows (see https://www.mathworks.com/help/matlab/ref/repelem.html#buocbhj-2):

e.g.: Create a matrix and repeat each element into a 3-by-2 block of a new matrix.

A = [1 2; 3 4]

B = repelem(A,3,2)

A = (2×2)
     1     2
     3     4

B = (6×4)
     1     1     2     2
     1     1     2     2
     1     1     2     2
     3     3     4     4
     3     3     4     4
     3     3     4     4

What is the best way to do the same in Numpy?

A = np.arange(1,5).reshape((2,2))
B = ...
like image 675
iterums Avatar asked Jan 27 '23 10:01

iterums


1 Answers

You can chain np.repeat specifying axis

repelem = lambda a, x, y: np.repeat(np.repeat(a, x, axis=0), y, axis=1)
# same as repelem  = lambda a, x, y: a.repeat(x, 0).repeat(y, 1)

Just call

>>> a = np.array([[1,2], [3,4]])
>>> repelem(a, 3, 2)

array([[1, 1, 2, 2],
       [1, 1, 2, 2],
       [1, 1, 2, 2],
       [3, 3, 4, 4],
       [3, 3, 4, 4],
       [3, 3, 4, 4]])
like image 180
rafaelc Avatar answered Jan 31 '23 22:01

rafaelc