Numpy: convert an array to a triangular matrix

2019-01-26 05:35发布

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?

1条回答
欢心
2楼-- · 2019-01-26 05:41
>>> 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.

查看更多
登录 后发表回答