python diag函數(shù)的作用是什么

小樊
86
2024-09-06 14:55:34

numpy.diag() 函數(shù)在 NumPy 庫(kù)中用于提取二維數(shù)組(矩陣)的對(duì)角線元素,或者創(chuàng)建一個(gè)新的對(duì)角線矩陣

  1. 提取對(duì)角線元素:當(dāng)傳入一個(gè)二維數(shù)組時(shí),numpy.diag() 函數(shù)會(huì)返回該數(shù)組的主對(duì)角線元素。例如:
import numpy as np

arr = np.array([[1, 2, 3], [4, 5, 6], [7, 8, 9]])
diag_elements = np.diag(arr)
print(diag_elements)  # 輸出:[1 5 9]
  1. 創(chuàng)建對(duì)角線矩陣:當(dāng)傳入一個(gè)一維數(shù)組時(shí),numpy.diag() 函數(shù)會(huì)根據(jù)該數(shù)組的元素創(chuàng)建一個(gè)新的對(duì)角線矩陣。例如:
import numpy as np

arr = np.array([1, 2, 3])
diag_matrix = np.diag(arr)
print(diag_matrix)
# 輸出:
# [[1 0 0]
#  [0 2 0]
#  [0 0 3]]

注意:numpy.diag() 函數(shù)還有一些其他參數(shù),如 k,可以用來(lái)指定要提取或創(chuàng)建的對(duì)角線的位置。正值表示上對(duì)角線,負(fù)值表示下對(duì)角線。

0