NumPy - 创建具有递增幂对角线的上三角矩阵

问题描述 投票:0回答:2

我想创建一个方上三角矩阵,对于某些浮点

c
和某些维度
N

定义如下
[[1 , c , c^2, ... c^N],
 [0,  1 ,   c, ... c^{N-1}],
 [0,  0 ,   1, ... c^{N-2}],
 .
 .
 .
 [0,  0 ,   0, ....    1]]

具体来说,如果

N=2
,那么矩阵应该是

[[1, c],
 [0, 1]]

如果

N=3
,那么矩阵应该是:


[[1, c, c^2],
 [0, 1,   c],
 [0, 0,   1]]

我该怎么做?

python-3.x numpy triangular
2个回答
1
投票

这是一个简单的方法:

import numpy as np

c = 2
n = 5

r = np.arange(n + 1)
p = r - r[:, np.newaxis]
res = np.triu(c ** p.clip(min=0))
print(res)
# [[ 1  2  4  8 16 32]
#  [ 0  1  2  4  8 16]
#  [ 0  0  1  2  4  8]
#  [ 0  0  0  1  2  4]
#  [ 0  0  0  0  1  2]
#  [ 0  0  0  0  0  1]]

如果你想制作一个非常大的矩阵并想节省时间和内存,你也可以这样做:

import numpy as np

c = 2
n = 5

b = np.zeros(2 * n + 1, a.dtype)
b[n:] = c ** np.arange(n + 1)
s, = b.strides
res = np.lib.stride_tricks.as_strided(b[n:], shape=(n + 1, n + 1), strides=(-s, s),
                                      writeable=False)
print(res)
# [[ 1  2  4  8 16 32]
#  [ 0  1  2  4  8 16]
#  [ 0  0  1  2  4  8]
#  [ 0  0  0  1  2  4]
#  [ 0  0  0  0  1  2]
#  [ 0  0  0  0  0  1]]

0
投票
import numpy as np

n = 5
c = 2

# Get indices for upper triangular part
indices = np.triu_indices(n)
row_indices = indices[0]
col_indices = indices[1]
print(row_indices)  # Output: [0 0 0 0 0 1 1 1 1 2 2 2 3 3 4]
print(col_indices)  # Output: [0 1 2 3 4 1 2 3 4 2 3 4 3 4 4]

powers =  np.arange(n)[col_indices - row_indices]
print(powers) 
'''
[0 1 2 3 4 0 1 2 3 0 1 2 0 1 0]
'''
matrix = np.eye(n)
print(matrix)
'''
[[1. 0. 0. 0. 0.]
 [0. 1. 0. 0. 0.]
 [0. 0. 1. 0. 0.]
 [0. 0. 0. 1. 0.]
 [0. 0. 0. 0. 1.]]
'''
matrix[indices] = c ** powers
print(matrix)
'''
[[ 1.  2.  4.  8. 16.]
 [ 0.  1.  2.  4.  8.]
 [ 0.  0.  1.  2.  4.]
 [ 0.  0.  0.  1.  2.]
 [ 0.  0.  0.  0.  1.]]
'''
© www.soinside.com 2019 - 2024. All rights reserved.