pratikm pratikm - 1 month ago 11
Python Question

extract upper/lower triangular part of a numpy matrix?

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

Answer

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

Comments