19

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?

tbrittoborges
  • 965
  • 1
  • 6
  • 16

1 Answers1

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

Fred Foo
  • 355,277
  • 75
  • 744
  • 836