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]])
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]])
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.