How to use== operator in R Language
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
# create 5*5 matrix. matrix_data= matrix (1:25,nrow=5,ncol=5) # display actual matrix print (matrix_data) # assign value to 1 matrix_data[ row (matrix_data)== col (matrix_data)] =1 # display final matrix_data |
Output:
Example 2:
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 matrix_data[ row (matrix_data)== col (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.
Contact Us