Method 2 : Using diag() methods
diag() is used to get the diagonal elements and we will set the value to 1.
Syntax: diag(matrix)=1
where, matrix is the input matrix.
Example:
In this example, we will create 2*2 matrix and assign 1 to the diagonal elements.
R
# create 2*2 matrix. matrix_data= matrix (1:4,nrow=2,ncol=2) # display actual matrix print (matrix_data) # assign value to 1 diag (matrix_data)=1 # display final matrix_data |
Output:
How to Set the Diagonal Elements of a Matrix to 1 in R?
In this article, we will discuss how to set the diagonal elements of a Matrix to 1 in R Programming Language.
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.