Calculate Trace of a Matrix in R Programming – tr() Function
Last Updated :
19 Jun, 2020
tr()
function in R Language is used to calculate the trace of a matrix. Trace of a matrix is the sum of the values on the main diagonal(upper left to lower right) of the matrix.
Syntax: tr(x)
Parameters:
x: Matrix
Example 1:
library(psych)
A = matrix(
c( 6 , 1 , 1 , 4 , - 2 , 5 , 2 , 8 , 7 ),
nrow = 3 ,
ncol = 3 ,
byrow = TRUE
)
A
cat( "Trace of A:\n" )
tr(A)
|
Output:
[, 1] [, 2] [, 3]
[1, ] 6 1 1
[2, ] 4 -2 5
[3, ] 2 8 7
Trace of A:
[1] 11
Example 2:
library(psych)
A = matrix(c( 1 : 9 ), 3 , 3 )
A
cat( "Trace of A:\n" )
tr(A)
|
Output:
[, 1] [, 2] [, 3]
[1, ] 1 4 7
[2, ] 2 5 8
[3, ] 3 6 9
Trace of A:
[1] 15
Like Article
Suggest improvement
Share your thoughts in the comments
Please Login to comment...