Open In App

How to Extract Diagonal Elements of a Matrix in R Without Using diag Function?

Last Updated : 02 Jun, 2022
Improve
Improve
Like Article
Like
Save
Share
Report

In this article, we will see how to extract diagonal elements of a matrix in R Programming Language without using diag() function.

Matrix is a rectangular arrangement of numbers in rows and columns. In a matrix, as we know rows are the ones that run horizontally and columns are the ones that run vertically. In R programming, matrices are two-dimensional, homogeneous data structures.

matrix[row(matrix)==col(matrix)]

where, matrix is the input matrix. row() will check row elements and col() will check column elements.

Example 1:

In this example, we will create 5*5 matrix and display the diagonal elements.

R




# create 5*5 matrix.
matrix_data=matrix(1:25,nrow=5,ncol=5)
  
# display actual matrix
print(matrix_data)
  
# extract diagonal elements
matrix_data[row(matrix_data)==col(matrix_data)]


Output:

     [,1] [,2] [,3] [,4] [,5]
[1,]    1    6   11   16   21
[2,]    2    7   12   17   22
[3,]    3    8   13   18   23
[4,]    4    9   14   19   24
[5,]    5   10   15   20   25
[1]  1  7 13 19 25

Example 2:

In this example, we will create 3*3 matrix and display the diagonal elements.

R




# create 3*3 matrix.
matrix_data = matrix(c(1, 3, 4, 5, 6, 7, 9, 6, 3),
                     nrow=3, ncol=3)
  
# display actual matrix
print(matrix_data)
  
# extract diagonal elements
matrix_data[row(matrix_data) == col(matrix_data)]


Output:

     [,1] [,2] [,3]
[1,]    1    5    9
[2,]    3    6    6
[3,]    4    7    3
[1] 1 6 3

Like Article
Suggest improvement
Previous
Next
Share your thoughts in the comments

Similar Reads