Is there a function in numpy/scipy that returns all the elements of one of the triangles (upper or lower) of a square matrix?
e.g.:
matrix = [[1, 2, 3],
[4, 5, 6],
[7, 8, 9]]
triangles (upper and lower):
up = [1,2,3,5,6,9]
down = [1,4,5,7,8,9]
or
up = [1,2,5,3,6,9]
down = [1,4,7,5,8,9]
Thank you!
EDIT:
Yes there are two functions that help you do that: np.triu_indices(n) (for the upper triangle) and np.tril_indices(n) (for the lower triangle).
Thanks katrielalex!
Does the order of the elements matter?
Normally the upper and lower triangles of a matrix are taken about the other diagonal (top left to bottom right). To fix that, you need to “flip” between the two diagonals, which you can do with
np.fliplr(matrix). That will get you the correct elements, but in the “natural” order (row-by-row, with each row getting shorter). You can also get the column-by-column order by flipping the other way (np.flipud). But I don’t know any way to get the “reading by smaller diagonals” order that you are using, short of reading the matrix one diagonal at a time.To get the diagonal elements you can get their indices with
np.triu_indices(or, for the lower triangle,np.tril_indices) and then index by them.