Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Numpy: convert an array to a triangular matrix

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?

like image 976
tbrittoborges Avatar asked Nov 18 '13 18:11

tbrittoborges


People also ask

How do you create a lower triangular matrix in Numpy?

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.

How do you convert a matrix to a Numpy 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.


1 Answers

>>> 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.

like image 50
Fred Foo Avatar answered Sep 20 '22 12:09

Fred Foo