Setting Diagonal of a Rectangular Matrix to Zero
When matrix is of N x M i.e. different no. of rows and different no. of columns.
Syntax :
matrix_1 <- matrix(sequence, nrow, ncol)
- sequence: sequence of numbers
- nrow: number of rows
- ncol: number of columns
R
# Form 4x3 matrix matrix_1 <- matrix (3:14, nrow = 4, ncol = 3) # Print the original matrix cat ( "Given Matrix:\n" ) print (matrix_1) # Set the diagonal elements along the shorter dimension to zero if ( nrow (matrix_1) >= ncol (matrix_1)) { diag (matrix_1[, 1: ncol (matrix_1)]) <- 0 } else { diag (matrix_1[1: nrow (matrix_1), ]) <- 0 } # Output cat ( "\nModified Matrix :\n" ) print (matrix_1) |
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.
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.