Reputation: 55
Is it possible to take a 1D numpy array containing 171 values and place these values into the top triangle of an 18X18 matrix?
I feel like I should be able to use np.triu_indices to do this somehow but I can't quite figure it out!
Thanks!
Upvotes: 5
Views: 1555
Reputation: 231385
See What is the most efficient way to get this kind of matrix from a 1D numpy array? and Copy flat list of upper triangle entries to full matrix?
Roughly the approach is
result = np.zeros(...)
ind = np.triu_indices(...)
result[ind] = values
Details depend on the size of the target array, and the layout of your values in the target.
In [680]: ind = np.triu_indices(4)
In [681]: values = np.arange(16).reshape(4,4)[ind]
In [682]: result = np.zeros((4,4),int)
In [683]: result[ind]=values
In [684]: values
Out[684]: array([ 0, 1, 2, 3, 5, 6, 7, 10, 11, 15])
In [685]: result
Out[685]:
array([[ 0, 1, 2, 3],
[ 0, 5, 6, 7],
[ 0, 0, 10, 11],
[ 0, 0, 0, 15]])
Upvotes: 5