Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Extract upper or lower triangular part of a numpy matrix

Tags:

python

numpy

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.]]) 
like image 552
pratikm Avatar asked Jan 18 '12 05:01

pratikm


People also ask

How do you extract upper triangular 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.

How do you get the upper triangular matrix in NumPy?

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.

How do you find the upper and lower triangular matrix?

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.

How do you print 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.


2 Answers

Try numpy.triu (triangle-upper) and numpy.tril (triangle-lower).

like image 74
mathematical.coffee Avatar answered Oct 01 '22 05:10

mathematical.coffee


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.


IMPORTANT

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]) 

EDIT (on 11.11.2019):

To put back the extracted vector into a 2D symmetric array, one can follow my answer here: https://stackoverflow.com/a/58806626/5025009

like image 27
seralouk Avatar answered Oct 01 '22 05:10

seralouk