gpt4 book ai didi

python - 如何使用numpy获取没有对角线的三角形上矩阵

转载 作者:行者123 更新时间:2023-12-04 13:30:47 32 4
gpt4 key购买 nike

可以说我有以下矩阵:

A = np.array([
[1,2,3],
[4,5,6],
[7,8,9]])

如何在没有对角线的情况下有效地提取上三角矩阵?
输出将是以下数组:
B = np.array([2,3,6])

最佳答案

一种掩盖的方法-

def upper_tri_masking(A):
m = A.shape[0]
r = np.arange(m)
mask = r[:,None] < r
return A[mask]

另一个与 np.triu_indices -
def upper_tri_indexing(A):
m = A.shape[0]
r,c = np.triu_indices(m,1)
return A[r,c]

sample 运行-
In [403]: A
Out[403]:
array([[79, 17, 79, 58, 14],
[87, 63, 89, 26, 31],
[69, 34, 90, 24, 96],
[59, 60, 80, 52, 46],
[75, 80, 11, 61, 47]])

In [404]: upper_tri_masking(A)
Out[404]: array([17, 79, 58, 14, 89, 26, 31, 24, 96, 46])

运行时测试-
In [415]: A = np.random.randint(0,9,(5000,5000))

In [416]: %timeit upper_tri_masking(A)
10 loops, best of 3: 64.2 ms per loop

In [417]: %timeit upper_tri_indexing(A)
1 loop, best of 3: 252 ms per loop

关于python - 如何使用numpy获取没有对角线的三角形上矩阵,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47314754/

32 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com