Python - How can I find the square matrix of a lower numpy triangular matrix? (with symmetrical upper triangle)

I created a lower triangular matrix, and I want to complete the matrix using the values โ€‹โ€‹in the lower triangular matrix to form a square matrix symmetrical around diagonal zeros.

lower_triangle = numpy.array([ [0,0,0,0], [1,0,0,0], [2,3,0,0], [4,5,6,0]]) 

I want to generate the following full matrix, maintaining a zero diagonal:

 complete_matrix = numpy.array([ [0, 1, 2, 4], [1, 0, 3, 5], [2, 3, 0, 6], [4, 5, 6, 0]]) 

Thanks.

+7
source share
2 answers

You can simply add it to its transpose:

 >>> m array([[0, 0, 0, 0], [1, 0, 0, 0], [2, 3, 0, 0], [4, 5, 6, 0]]) >>> m + mT array([[0, 1, 2, 4], [1, 0, 3, 5], [2, 3, 0, 6], [4, 5, 6, 0]]) 
+9
source

You can use numpy.triu_indices or numpy.tril_indices:

 >>> a=np.array([[0, 0, 0, 0], ... [1, 0, 0, 0], ... [2, 3, 0, 0], ... [4, 5, 6, 0]]) >>> irows,icols = np.triu_indices(len(a),1) >>> a[irows,icols]=a[icols,irows] >>> a array([[0, 1, 2, 4], [1, 0, 3, 5], [2, 3, 0, 6], [4, 5, 6, 0]]) 
+7
source

All Articles