I have an array A
with shape (N,). I am taking N=5 for illustration:
A = np.array([0,1,1,0,1])
And I want to transform it to the following NxN matrix B
. Solutions in both NumPy and Tensorflow are good but the latter is preferred.
B = np.array([[0,1,1,0,1],
[0,1,1,0,1],
[0,1,1,0,1],
[0,0,0,0,1],
[0,0,0,0,1]])
One solution can be comprised of following steps:
A
N timesi
. Look for the index of the last zero until the i-th
element of that row.Another illustration with N=10:
D = np.array([0,1,1,1,0,0,1,1,0,0])
E = np.array([[0,1,1,1,0,0,1,1,0,0],
[0,1,1,1,0,0,1,1,0,0],
[0,1,1,1,0,0,1,1,0,0],
[0,1,1,1,0,0,1,1,0,0],
[0,0,0,0,0,0,1,1,0,0],
[0,0,0,0,0,0,1,1,0,0],
[0,0,0,0,0,0,1,1,0,0],
[0,0,0,0,0,0,1,1,0,0],
[0,0,0,0,0,0,0,0,0,0],
[0,0,0,0,0,0,0,0,0,0]])
A = np.array([0,1,1,0,1])
N = A.shape[0]
column = (A > 0).reshape((N, 1))
mask = np.ones((N, N), dtype=np.bool)
mask = np.where(column, False, np.tril(mask, -1))
mask = np.cumsum(mask, axis=0)
B = np.where(mask, 0, np.tile(A, (N, 1)))
[[0 1 1 0 1]
[0 1 1 0 1]
[0 1 1 0 1]
[0 0 0 0 1]
[0 0 0 0 1]]
[[False False False False False]
[ True False False False False]
[ True True False False False]
[ True True True False False]
[ True True True True False]]
[[False False False False False]
[False False False False False]
[False False False False False]
[ True True True False False]
[False False False False False]]
[[0 0 0 0 0]
[0 0 0 0 0]
[0 0 0 0 0]
[1 1 1 0 0]
[1 1 1 0 0]]
[[0 1 1 0 1]
[0 1 1 0 1]
[0 1 1 0 1]
[0 1 1 0 1]
[0 1 1 0 1]]
[[0 1 1 0 1]
[0 1 1 0 1]
[0 1 1 0 1]
[0 0 0 0 1]
[0 0 0 0 1]]