user1658296 - 1 year ago 302
Python Question

# 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)?

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]])
``````
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download