在 R 编程中计算矩阵的迹 - tr()函数
R语言中的tr()
函数用于计算矩阵的迹。矩阵的迹是矩阵的主对角线(左上到右下)上的值的总和。
Syntax: tr(x)
Parameters:
x: Matrix
示例 1:
# R program to calculate
# trace of a matrix
# Loading library
library(psych)
# Creating a matrix
A = matrix(
c(6, 1, 1, 4, -2, 5, 2, 8, 7),
nrow = 3,
ncol = 3,
byrow = TRUE
)
A
# Calling tr() function
cat("Trace of A:\n")
tr(A)
输出:
[, 1] [, 2] [, 3]
[1, ] 6 1 1
[2, ] 4 -2 5
[3, ] 2 8 7
Trace of A:
[1] 11
示例 2:
# R program to calculate
# trace of a matrix
# Loading library
library(psych)
# Creating a matrix
A = matrix(c(1:9), 3, 3)
A
# Calling tr() function
cat("Trace of A:\n")
tr(A)
输出:
[, 1] [, 2] [, 3]
[1, ] 1 4 7
[2, ] 2 5 8
[3, ] 3 6 9
Trace of A:
[1] 15