Open In App

How to Set the Diagonal Elements of a Matrix to 1 in R?

Last Updated : 02 Jun, 2022
Improve
Improve
Like Article
Like
Save
Share
Report

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




# 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:

 

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:

 



Like Article
Suggest improvement
Previous
Next
Share your thoughts in the comments

Similar Reads