Setting Diagonal of a Square Matrix to Zero
When matrix is of N x N i.e. same no of rows and same no of columns
Syntax :
matrix_1 <- matrix(sequence ,nrow)
- sequence: sequence of numbers
- nrow: number of rows
R
# Print a sample 4x4 matrix matrix_1 <- matrix (1:25, nrow = 5) # Print the original matrix cat ( "Original Matrix:\n" ) print (matrix_1) # Set the diagonal elements to zero diag (matrix_1) <- 0 # Print the modified matrix cat ( "\nModified Matrix :\n" ) print (matrix_1) |
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
Modified Matrix :
[,1] [,2] [,3] [,4] [,5]
[1,] 0 6 11 16 21
[2,] 2 0 12 17 22
[3,] 3 8 0 18 23
[4,] 4 9 14 0 24
[5,] 5 10 15 20 0
We create a square matrix using matrix() with number of rows to be 4 and sequence being from 1-25. We use diag(matrix_1) <- 0, this function used to access the diagonal elements of matrix which is from top left to bottom right and returns a vector containing the diagonal elements of the matrix where all diagonal elements are zero.
Set Diagonal of a Matrix to zero in R
Matrices are fundamental data structures in R that allow you to store and manipulate two-dimensional data. If you want to set diagonal element of matrix to zero in R programming language then you have to follow these steps to attain it.