I was looking for a built in method to convert an linear array to triangular matrix. As I failed in find one I am asking for help in implementing one.
Imagine an array like:
In [203]: dm
Out[203]: array([ 0.80487805, 0.90243902, 0.85365854, ..., 0.95121951,
0.90243902, 1. ])
In [204]: dm.shape
Out[204]: (2211,)
And I would like to convert this array to a an triangular matrix or a symmetric rectangular matrix.
In [205]: reshapedDm = dm.trian_reshape(67, 67)
How I would implement trian_reshape as function that returns an triangular matrix from 1-D array?
To create an array with zero above the main diagonal forming a lower triangular matrix, use the numpy. tri() method in Python Numpy. The 1st parameter is the number of rows in the array. The 2nd parameter is the number of columns in the array.
We can use numpy. flatten() function to convert the matrix to an array. It takes all N elements of the matrix placed into a single dimension array.
>>> tri = np.zeros((67, 67))
>>> tri[np.triu_indices(67, 1)] = dm
See doc for triu_indices
for details. To get a lower-triangular matrix, use np.tril_indices
and set the offset to -1
instead of 1
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With