![]() |
VOOZH | about |
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.
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.
Output:
[,1] [,2] [,3] [1,] 1 5 9 [2,] 3 6 6 [3,] 4 7 3 [1] 1 6 3