Tom*_*ett 13 python arrays numpy matrix toeplitz
我正在尝试制作一个看起来像这样的numpy数组:
[a b c ]
[ a b c ]
[ a b c ]
[ a b c ]
Run Code Online (Sandbox Code Playgroud)
所以这涉及更新主对角线和它上面的两个对角线.
这样做的有效方法是什么?
Sau*_*tro 19
您可以使用np.indices
获取数组的索引,然后将值分配给所需的值.
a = np.zeros((5,10))
i,j = np.indices(a.shape)
Run Code Online (Sandbox Code Playgroud)
i,j
分别是行索引和列索引.
a[i==j] = 1.
a[i==j-1] = 2.
a[i==j-2] = 3.
Run Code Online (Sandbox Code Playgroud)
将导致:
array([[ 1., 2., 3., 0., 0., 0., 0., 0., 0., 0.],
[ 0., 1., 2., 3., 0., 0., 0., 0., 0., 0.],
[ 0., 0., 1., 2., 3., 0., 0., 0., 0., 0.],
[ 0., 0., 0., 1., 2., 3., 0., 0., 0., 0.],
[ 0., 0., 0., 0., 1., 2., 3., 0., 0., 0.]])
Run Code Online (Sandbox Code Playgroud)
这是Toeplitz矩阵的一个例子- 您可以使用scipy.linalg.toeplitz
以下方法构建它:
import numpy as np
from scipy.linalg import toeplitz
first_row = np.array([1, 2, 3, 0, 0, 0])
first_col = np.array([1, 0, 0, 0])
print(toeplitz(first_col, first_row))
# [[1 2 3 0 0 0]
# [0 1 2 3 0 0]
# [0 0 1 2 3 0]
# [0 0 0 1 2 3]]
Run Code Online (Sandbox Code Playgroud)
归档时间: |
|
查看次数: |
6916 次 |
最近记录: |