NumPy trace()

numpy.trace() 函数用于返回矩阵对角线元素的总和。

示例

import numpy as np

# create a 2D matrix
matrix = np.array([[1, 2], 
                   [4, 6]])

# calculate the trace of the matrix result = np.trace(matrix)
print(result) # Output: 7

trace() 语法

trace() 的语法是:

numpy.trace(matrix, offset=0, dtype=None, out=None)

trace() 参数

trace() 方法接受以下参数:

  • matrix - 从中提取对角线的输入矩阵
  • offset (可选) - 对角线相对于主对角线的偏移量
  • dtype (可选) - 确定返回矩阵的数据类型

trace() 返回值

trace() 方法返回 matrix 对角线元素的总和。


示例 1:计算矩阵的迹

import numpy as np

# create a matrix
matrix1 = np.array([[1, 2, 3], 
                    [4, 5, 6], 
                    [7, 8, 9]])

# calculate the trace of the matrix and return integer value result = np.trace(matrix1, dtype=int)
print(result)

输出

15

在上面的示例中,矩阵的迹是 matrix1 对角线上元素的总和(即 1 + 5 + 9 = 15)。


示例 2:trace() 中 offset 参数的使用

import numpy as np

# create a matrix
matrix1 = np.array([[1, 2, 3], 
                    [4, 5, 6], 
                    [7, 8, 9]])

# calculate trace of the matrix with offset 1
result1 = np.trace(matrix1, offset=1)
print("With offset=1:", result1)  # Output: 8 (2 + 6)

# calculate trace of the matrix with offset -1
result2 = np.trace(matrix1, offset=-1)
print("With offset=-1:", result2) # Output: 12 (4 + 8)

输出

With offset=1: 8
With offset=-1: 12

这里,

  • 如果将 offset 设置为正整数,函数将计算主对角线上方的对角线元素的总和。
  • 如果将 offset 设置为负整数,函数将计算主对角线下方对角线元素的总和。

我们的高级学习平台,凭借十多年的经验和数千条反馈创建。

以前所未有的方式学习和提高您的编程技能。

试用 Programiz PRO
  • 交互式课程
  • 证书
  • AI 帮助
  • 2000+ 挑战