# Calculate Trace of a Matrix in R Programming – tr() Function

`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:

 `# 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) `

Output:

```     [, 1] [, 2] [, 3]
[1, ]    6    1    1
[2, ]    4   -2    5
[3, ]    2    8    7
Trace of A:
 11
```

Example 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) `

Output:

```     [, 1] [, 2] [, 3]
[1, ]    1    4    7
[2, ]    2    5    8
[3, ]    3    6    9
Trace of A:
 15
```

My Personal Notes arrow_drop_up Check out this Author's contributed articles.

If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.

Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.

Article Tags :

Be the First to upvote.

Please write to us at contribute@geeksforgeeks.org to report any issue with the above content.