user1658296
user1658296

Reputation: 1418

Numpy: create a matrix from smaller matrices

Is there a way using numpy to create a square matrix M from a smaller square matrix m?

Assuming that the shape of M is evenly divisible by shape of m (2x2):

 m = [[1, 2],
      [3, 4]]

From m, I want to build a matrix of shape 4x4, such that:

array([[ 1.,  2.,  1.,  2.],
       [ 3.,  4.,  3.,  4.],
       [ 1.,  2.,  1.,  2.],
       [ 3.,  4.,  3.,  4.]])

is created.

I am aware of how to create a matrix of a particular shape and initialize it with a scalar:

numpy.full((4,4), 0, dtype=numpy.int)

Here, I want to build with an existing array. How might this be achieved (and efficiently)?

Upvotes: 3

Views: 662

Answers (2)

Divakar
Divakar

Reputation: 221614

We can use NumPy's Kronecker product -

np.kron(np.ones((2, 2), dtype=int), m)

Sample run -

In [140]: m
Out[140]: 
array([[1, 2],
       [3, 4]])

In [141]: np.kron(np.ones((2, 2), dtype=int), m)
Out[141]: 
array([[1, 2, 1, 2],
       [3, 4, 3, 4],
       [1, 2, 1, 2],
       [3, 4, 3, 4]])

Upvotes: 5

Francisco
Francisco

Reputation: 11496

Use np.tile:

>>> np.tile(arr, (2, 2))
array([[1, 2, 1, 2],
       [3, 4, 3, 4],
       [1, 2, 1, 2],
       [3, 4, 3, 4]])

Upvotes: 4

Related Questions