Python 如何使用numpy创建下对角线矩阵?
如何使用Numpy生成动态大小的下对角矩阵? 例如,如果矩阵的大小n为4,我希望得到这样一个矩阵:Python 如何使用numpy创建下对角线矩阵?,python,numpy,matrix,Python,Numpy,Matrix,如何使用Numpy生成动态大小的下对角矩阵? 例如,如果矩阵的大小n为4,我希望得到这样一个矩阵: | 0 0 0 0 | | 1 0 0 0 | | 0 1 0 0 | | 0 0 1 0 | 您可以创建它,首先创建一个包含零的矩阵,然后填充一: import numpy as np # create matrix with zeros n=4 mat = np.zeros((n,n)) # create indexes for where the 1s belong rows = np
| 0 0 0 0 |
| 1 0 0 0 |
| 0 1 0 0 |
| 0 0 1 0 |
您可以创建它,首先创建一个包含零的矩阵,然后填充一:
import numpy as np
# create matrix with zeros
n=4
mat = np.zeros((n,n))
# create indexes for where the 1s belong
rows = np.arange(1,n)
cols = np.arange(n-1)
# fill in the 1s
mat[rows, cols] = 1
输出:
[[0. 0. 0. 0.]
[1. 0. 0. 0.]
[0. 1. 0. 0.]
[0. 0. 1. 0.]]
您可以创建它,首先创建一个包含零的矩阵,然后填充一:
import numpy as np
# create matrix with zeros
n=4
mat = np.zeros((n,n))
# create indexes for where the 1s belong
rows = np.arange(1,n)
cols = np.arange(n-1)
# fill in the 1s
mat[rows, cols] = 1
输出:
[[0. 0. 0. 0.]
[1. 0. 0. 0.]
[0. 1. 0. 0.]
[0. 0. 1. 0.]]
我找到了最短的使用方法: 输出为:
array([[0, 0, 0, 0],
[1, 0, 0, 0],
[0, 1, 0, 0],
[0, 0, 1, 0]])
我找到了最短的使用方法: 输出为:
array([[0, 0, 0, 0],
[1, 0, 0, 0],
[0, 1, 0, 0],
[0, 0, 1, 0]])