In this article, we will discuss how to create an Identity Matrix in R Programming Language.
Identity matrices are the matrices that contain all the zeros, except diagonal elements which are equivalent to 1. The identity matrices are always square in nature. Base R provides a large number of methods to create and define the identity matrices in R :
Method 1: Using diag method
The diag() method in base R is used to create a square matrix with the specified dimensions. It assigns the diagonal value to 1 and rest all the elements are assigned a value of 0.
Syntax:
diag(num)
where, num – The number equivalent to the number of rows and columns of the matrix.
Example:
# creating a diagonal matrix with # dimensions 3 x 3 diag_mat < - diag (3)
# printing identity matrix print ( "Identity Matrix" )
print (diag_mat)
|
Output:
[1] "Identity Matrix" [,1] [,2] [,3] [1,] 1 0 0 [2,] 0 1 0 [3,] 0 0 1
Method 2: Using diag(nrow) method
The diag(nrow) method can be used to specify the number of rows of the identity matrix. It assigns the number of columns equivalent to the specified number of rows.
Syntax:
diag(nrow = )
where, nrow – The number of rows of the identity matrix
Example:
# creating a diagonal matrix with # dimensions 7 x 7 diag_mat < - diag (nrow=7)
# printing identity matrix print ( "Identity Matrix" )
print (diag_mat)
|
Output:
[1] "Identity Matrix" > print(diag_mat) [,1] [,2] [,3] [,4] [,5] [,6] [,7] [1,] 1 0 0 0 0 0 0 [2,] 0 1 0 0 0 0 0 [3,] 0 0 1 0 0 0 0 [4,] 0 0 0 1 0 0 0 [5,] 0 0 0 0 1 0 0 [6,] 0 0 0 0 0 1 0 [7,] 0 0 0 0 0 0 1
Method 3: Creating a matrix of zeros and then assigning diagonals to 1
The matrix() method in R can be used to create a matrix with a specified value and assign it to the number of declared rows and columns of the matrix.
Syntax:
matrix ( val , rows, cols)
Parameters :
- val – The value to be assigned to all the cells
- rows – The rows of the identity matrix
- cols – The columns of the identity matrix
Example:
We initially create a matrix of 0’s and then the diagonals are assigned 1’s using the diag() method defined earlier.
# defining number of rows and columns row < - 6 col < - 6 # creating a diagonal matrix with # dimensions 6 x 6 diag_mat < - matrix (0, row, col)
# specifying the diagonal value to be 1 diag (diag_mat) < - 1
# printing identity matrix print ( "Identity Matrix" )
print (diag_mat)
|
Output:
[1] "Identity Matrix" > print(diag_mat) [,1] [,2] [,3] [,4] [,5] [,6] [1,] 1 0 0 0 0 0 [2,] 0 1 0 0 0 0 [3,] 0 0 1 0 0 0 [4,] 0 0 0 1 0 0 [5,] 0 0 0 0 1 0 [6,] 0 0 0 0 0 1