如何使用 Numpy 创建一个单位矩阵?


在此程序中,我们将打印一个 nxn 大小的单位矩阵,其中 n 将从用户那里获取。我们应当在 numpy 库中使用 identity() 函数,该函数将维度和元素的数据类型作为参数

算法

Step 1: Import numpy.
Step 2: Take dimensions as input from the user.
Step 3: Print the identity matrix using numpy.identity() function.

示例代码

import numpy as np

dimension = int(input("Enter the dimension of identitiy matrix: "))
identity_matrix = np.identity(dimension, dtype="int")
print(identity_matrix)

输出

Enter the dimension of identitiy matrix: 5
[[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]]

更新时间:2021 年 3 月 16 日

4K+ 浏览量

职业生涯开好头

完成课程获得认证

开始使用
广告
© . All rights reserved.