To extract the diagonal of a matrix in R, you can use the diag()
function. This function retrieves the diagonal elements of a matrix as a vector.
In this example,
matrix1
using the matrix()
function with a vector of values c(1, 2, 3, 4)
and specify the number of rows as 2.diag()
function on matrix1
and store the result in a variable called diagonal1
.diag()
function returns a vector containing the diagonal elements of the matrix.print()
function to display the diagonal elements stored in diagonal1
.matrix1 <- matrix(c(1, 2, 3, 4), nrow = 2)
diagonal1 <- diag(matrix1)
print(diagonal1)
[1] 1 4
In this example,
matrix2
using the matrix()
function with a vector of values c(1, 2, 3, 4, 5, 6, 7, 8, 9)
and specify the number of rows as 3.diag()
function on matrix2
and store the result in a variable called diagonal2
.diag()
function returns a vector containing the diagonal elements of the matrix.print()
function to display the diagonal elements stored in diagonal2
.matrix2 <- matrix(c(1, 2, 3, 4, 5, 6, 7, 8, 9), nrow = 3)
diagonal2 <- diag(matrix2)
print(diagonal2)
[1] 1 5 9
In this example,
matrix3
using the matrix()
function with a vector of values c(10, 20, 30, 40, 50, 60, 70, 80, 90, 100, 110, 120, 130, 140, 150, 160)
and specify the number of rows as 4.diag()
function on matrix3
and store the result in a variable called diagonal3
.diag()
function returns a vector containing the diagonal elements of the matrix.print()
function to display the diagonal elements stored in diagonal3
.matrix3 <- matrix(c(10, 20, 30, 40, 50, 60, 70, 80, 90, 100, 110, 120, 130, 140, 150, 160), nrow = 4)
diagonal3 <- diag(matrix3)
print(diagonal3)
[1] 10 60 110 160
In this tutorial, we learned How to Extract the Diagonal of a Matrix in R language with well detailed examples.