在python中获取方矩阵的上三角或下三角的所有元素 [英] Get all elements of the upper or lower triangle of a square matrix in python
问题描述
在numpy/scipy中是否有一个函数可以返回方矩阵的三角形之一(上或下)的所有元素?
Is there a function in numpy/scipy that returns all the elements of one of the triangles (upper or lower) of a square matrix?
例如:
matrix = [[1, 2, 3],
[4, 5, 6],
[7, 8, 9]]
三角形(上下):
up = [1,2,3,5,6,9]
down = [1,4,5,7,8,9]
或
up = [1,2,5,3,6,9]
down = [1,4,7,5,8,9]
谢谢!
是的,有两个功能可以帮助您做到这一点:np.triu_indices(n)
(用于上部三角形)和np.tril_indices(n)
(用于下部三角形).
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).
感谢katrielalex!
Thanks katrielalex!
推荐答案
元素的顺序重要吗?
通常,矩阵的上下三角形围绕 other 对角线(从左上方到右下方)获取.要解决此问题,您需要在两个对角线之间翻转",这可以使用np.fliplr(matrix)
进行.这将为您提供正确的元素,但顺序为自然"(逐行,每行越来越短).您还可以通过翻转另一种方式(np.flipud
)获得逐列顺序.但是我不知道有什么方法可以获取正在使用的按较小的对角线读数"的顺序,而不能一次读取一个对角线的矩阵.
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.
要获取对角线元素,可以使用np.triu_indices
(对于下部三角形为np.tril_indices
)获取它们的索引,然后通过它们进行索引.
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.
>>> matrix
array([[1, 2, 3],
[4, 5, 6],
[7, 8, 9]])
>>> np.fliplr(matrix)[np.triu_indices(3)]
array([3, 2, 1, 5, 4, 7])
这篇关于在python中获取方矩阵的上三角或下三角的所有元素的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!