I have a matrix A
and I want 2 matrices U
and L
such that U
contains the upper triangular elements of A (all elements above and not including diagonal) and similarly for L
(all elements below and not including diagonal). Is there a numpy
method to do this?
e.g
A = array([[ 4., 9., -3.], [ 2., 4., -2.], [-2., -3., 7.]]) U = array([[ 0., 9., -3.], [ 0., 0., -2.], [ 0., 0., 0.]]) L = array([[ 0., 0., 0.], [ 2., 0., 0.], [-2., -3., 0.]])
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.
NumPy: triu() function Upper triangle of an array. The triu() function is used to get a copy of a matrix with the elements below the k-th diagonal zeroed. Number of rows in the array. Diagonal above which to zero elements.
A triangular matrix is a square matrix in which all elements above or below the main diagonal are zero (0). If all the entries above the main diagonal are zero, it is a lower triangular matrix. In contrast, if all the entries below the main diagonal are zero, it is an upper triangular matrix.
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.
Try numpy.triu
(triangle-upper) and numpy.tril
(triangle-lower).
To extract the upper triangle values to a flat vector, you can do something like the following:
import numpy as np a = np.array([[1,2,3],[4,5,6],[7,8,9]]) print(a) #array([[1, 2, 3], # [4, 5, 6], # [7, 8, 9]]) a[np.triu_indices(3)] #or list(a[np.triu_indices(3)]) #array([1, 2, 3, 5, 6, 9])
Similarly, for the lower triangle, use np.tril
.
If you want to extract the values that are above the diagonal (or below) then use the k argument. This is usually used when the matrix is symmetric.
import numpy as np a = np.array([[1,2,3],[4,5,6],[7,8,9]]) #array([[1, 2, 3], # [4, 5, 6], # [7, 8, 9]]) a[np.triu_indices(3, k = 1)] # this returns the following array([2, 3, 6])
To put back the extracted vector into a 2D symmetric array, one can follow my answer here: https://stackoverflow.com/a/58806626/5025009
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With