[英]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? 我如何实现trian_reshape作为从1-D数组返回三角矩阵的函数?
>>> tri = np.zeros((67, 67))
>>> tri[np.triu_indices(67, 1)] = dm
See doc for triu_indices
for details. 有关详细信息,请参阅triu_indices
doc 。 To get a lower-triangular matrix, use np.tril_indices
and set the offset to -1
instead of 1
. 要获得下三角矩阵,请使用np.tril_indices
并将偏移设置为-1
而不是1
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.