Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

I generated 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 the 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 complete matrix, maintaining the zero diagonal:

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

Thanks.

like image 408
Dana Gray Avatar asked Jun 30 '13 22:06

Dana Gray


People also ask

How do you find the lower triangular matrix in python?

Input : mat[4][4] = {{1, 0, 0, 0}, {1, 4, 0, 0}, {4, 6, 2, 0}, {0, 4, 7, 6}}; Output : Matrix is in lower triangular form. Input : mat[4][4] = {{1, 0, 0, 0}, {4, 3, 0, 1}, {7, 9, 2, 0}, {8, 5, 3, 6}}; Output : Matrix is not in lower triangular form.

What is upper triangular matrix and lower triangular matrix in python?

A square matrix is called lower triangular if all the entries above the main diagonal are zero. Upper Triangular Matrix. A square matrix is called upper triangular if all the entries below the main diagonal are zero. A matrix of the form. L=[ℓ1,10ell2,1ℓ2,2ell3,1ℓ3,2⋱vdots⋮⋱⋱elln,1ℓn,2…

How do you find the upper triangular of a matrix in python?

Python NumPy triu() is an inbuilt function that is used to return a copy of the array matrix with an element of the upper part of the triangle with respect to k.


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 + m.T
array([[0, 1, 2, 4],
       [1, 0, 3, 5],
       [2, 3, 0, 6],
       [4, 5, 6, 0]])
like image 200
DSM Avatar answered Nov 03 '22 10:11

DSM


You can use the 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]])
like image 33
rtrwalker Avatar answered Nov 03 '22 10:11

rtrwalker