How to Set the Diagonal Elements of a Matrix to 1 in R?
Last Updated :
02 Jun, 2022
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.
Method 1 : Using == operator
The syntax to assign value 1 to the diagonal elements is:
matrix[row(matrix)==col(matrix)]=1
Example 1:
In this example, we will create 5*5 matrix and assign 1 to the diagonal elements.
R
matrix_data= matrix (1:25,nrow=5,ncol=5)
print (matrix_data)
matrix_data[ row (matrix_data)== col (matrix_data)] =1
matrix_data
|
Output:
Example 2:
In this example, we will create 2*2 matrix and assign 1 to the diagonal elements.
R
matrix_data= matrix (1:4,nrow=2,ncol=2)
print (matrix_data)
matrix_data[ row (matrix_data)== col (matrix_data)] =1
matrix_data
|
Output:
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
matrix_data= matrix (1:4,nrow=2,ncol=2)
print (matrix_data)
diag (matrix_data)=1
matrix_data
|
Output:
Like Article
Suggest improvement
Share your thoughts in the comments
Please Login to comment...