如何使用 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.