2

I can easily convert a symmetric matrix to an array/1-d matrix of one of its triangular components using

A_symmetric = np.matrix([[1,2][2,3]])
A_array = A_symmetric[np.triu_indices(2)] == np.matrix([1,2,3])

(and similary with tril_indices)

But how can I reverse this operations, i.e. how do I get a symmetric matrix from the array/1-d matrix given by triu_indices?

Frank Vel
  • 1,202
  • 1
  • 13
  • 27

1 Answers1

1

If you are ok with arrays instead of matrices you could simply preallocate and assign:

>>> i, j = np.triu_indices(8)                                                                                       
>>> a = np.arange(i.size)                                                                                          

>>> M = np.empty((8, 8), a.dtype)
>>> M[i, j] = a                                                                                                     
>>> M[j, i] = a
>>> M                                                                                                               
array([[ 0,  1,  2,  3,  4,  5,  6,  7],                                                                            
       [ 1,  8,  9, 10, 11, 12, 13, 14],
       [ 2,  9, 15, 16, 17, 18, 19, 20],
       [ 3, 10, 16, 21, 22, 23, 24, 25],
       [ 4, 11, 17, 22, 26, 27, 28, 29],
       [ 5, 12, 18, 23, 27, 30, 31, 32],
       [ 6, 13, 19, 24, 28, 31, 33, 34],
       [ 7, 14, 20, 25, 29, 32, 34, 35]])
Paul Panzer
  • 51,835
  • 3
  • 54
  • 99