R语言 计算矩阵的轨迹 – tr()函数
R语言中的 tr() 函数用于计算矩阵的轨迹。矩阵的轨迹是矩阵的主对角线(左上角到右下角)上的数值之和。
语法: tr(x)
参数:
x: 矩阵
例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