![]() |
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. Concepts Related to the Topic:Matrix Diagonal: In NxN matrix, there are N diagonal elements. The diagonal of a matrix consist of elements running from the top-left to bottom-right corner. Indexing: We can access element of matrix by the indices of their row and column. Steps Needed:If we want to set Diagonal of a Matrix to zero in R you have to follow these simple steps : Steps 1 : Create a matrix you want to make diagonal elements zero. Steps 2 : use the diag() function in R to access the diagonal elements of matrix. Steps 3 : Now assign zero value to the diagonal elements of the matrix. Setting Diagonal of a Square Matrix to ZeroWhen matrix is of N x N i.e. same no of rows and same no of columns Syntax :
R
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. Setting Diagonal of a Rectangular Matrix to ZeroWhen matrix is of N x M i.e. different no. of rows and different no. of columns. Syntax :
R
Output: [,1] [,2] [,3]
[1,] 3 7 11
[2,] 4 8 12
[3,] 5 9 13
[4,] 6 10 14
Modified Matrix :
[,1] [,2] [,3]
[1,] 0 7 11
[2,] 4 0 12
[3,] 5 9 0
[4,] 6 10 14
We create a rectangular matrix with number of rows as 4 and number of columns as 3. diag(matrix_1) is 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. The conditional statement is used which checks if no. of row is greater than no. of column or not. ‘diag(matrix_1[, 1:ncol(matrix_1)]) <- 0 ‘ is used to set shorter diagonal element to zero. |
Reffered: https://www.geeksforgeeks.org
Geeks Premier League |
Type: | Geek |
Category: | Coding |
Sub Category: | Tutorial |
Uploaded by: | Admin |
Views: | 12 |