How to populate an 2D array from a list left to right with the diagonal being all zeroes
Question:
I have a list:
idmatrixlist=[0.61, 0.63, 0.54, 0.82, 0.58, 0.57]
I need to populate an array from left to right while maintaining the zeroes on the diagonal so that the resulting array looks like.
I have tried the following code but it results in the wrong ordering of the entries.
lowertriangleidmatrix = np.zeros((4,4))
indexer = np.tril_indices(4,k=-1)
lowertriangleidmatrix[indexer] = idmatrixlist
print(lowertriangleidmatrix)
result:
[[0. 0. 0. 0. ]
[0.61 0. 0. 0. ]
[0.63 0.54 0. 0. ]
[0.82 0.58 0.57 0. ]]
How can this be re-ordered?
Answers:
You can use triu_indices
and invert the x/y:
lowertriangleidmatrix = np.zeros((4, 4))
indexer = np.triu_indices(4, k=1)[::-1]
# (array([0, 0, 1, 0, 1, 2]), array([1, 2, 2, 3, 3, 3]))
lowertriangleidmatrix[indexer] = idmatrixlist
print(lowertriangleidmatrix)
Output:
[[0. 0. 0. 0. ]
[0.61 0. 0. 0. ]
[0.63 0.82 0. 0. ]
[0.54 0.58 0.57 0. ]]
I have a list:
idmatrixlist=[0.61, 0.63, 0.54, 0.82, 0.58, 0.57]
I need to populate an array from left to right while maintaining the zeroes on the diagonal so that the resulting array looks like.
I have tried the following code but it results in the wrong ordering of the entries.
lowertriangleidmatrix = np.zeros((4,4))
indexer = np.tril_indices(4,k=-1)
lowertriangleidmatrix[indexer] = idmatrixlist
print(lowertriangleidmatrix)
result:
[[0. 0. 0. 0. ]
[0.61 0. 0. 0. ]
[0.63 0.54 0. 0. ]
[0.82 0.58 0.57 0. ]]
How can this be re-ordered?
You can use triu_indices
and invert the x/y:
lowertriangleidmatrix = np.zeros((4, 4))
indexer = np.triu_indices(4, k=1)[::-1]
# (array([0, 0, 1, 0, 1, 2]), array([1, 2, 2, 3, 3, 3]))
lowertriangleidmatrix[indexer] = idmatrixlist
print(lowertriangleidmatrix)
Output:
[[0. 0. 0. 0. ]
[0.61 0. 0. 0. ]
[0.63 0.82 0. 0. ]
[0.54 0.58 0.57 0. ]]