'How can I replace 1s in one matrix with another sub matrix?
I have a matrix-like
[[1, 2],
[3, 4]]
and I want to replace the 1s in another matrix:
[[1, 0],
[1, 1]]
to make this matrix:
[[1, 2, 0, 0],
[3, 4, 0, 0],
[1, 2, 1, 2],
[3, 4, 3, 4]]
The 1s in the second matrix can be in any position, this is just an example.
How can I do this?
Solution 1:[1]
from scipy.linalg import kron
m1 = np.array([[1, 2],[3, 4]])
m2 = np.array([[1, 0], [1, 1]])
output:
kron(m2, m1)
array([[1, 2, 0, 0],
[3, 4, 0, 0],
[1, 2, 1, 2],
[3, 4, 3, 4]])
How does it work?
It takes two arrays of M, N and P, Q dimensions. Here, m2 and m1 with 2, 2 and 2, 2 dimensions.
Next, it multiplies the arrays in the following way:
m2[0,0]*m1 m2[0,1]*m1 ... m2[0,-1]*m1
m2[1,0]*m1 m2[1,1]*m1 ... m2[1,-1]*m1
...
m2[-1,0]*m1 m2[-1,1]*m1 ... m2[-1,-1]*m1
To create a single array of dimensions (M*P, N*Q)
Solution 2:[2]
You can do that elegantly with a mathematical operation called Kronecker product which is implemented in numpy (or in scipy using numpy underneath).
import numpy as np # or from scipy import linealg
a = np.array([[1, 0],
[1, 1]])
b = np.array([[1, 2],
[3, 4]])
np.kron(a, b) # or linealg.kron(a, b)
# returns
# array([[1, 2, 0, 0],
# [3, 4, 0, 0],
# [1, 2, 1, 2],
# [3, 4, 3, 4]])
And here is what the Kronecker product does mathematically:
In other words, with the matrix A (or numpy array a) we indicate if the entries of B shall be added (if 1) or not (if 0).
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Abhyuday Vaish |
| Solution 2 |

