python二维数组输出下三角,在python中获取方矩阵的上三角或下三角的所有元素

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.

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

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值