![]() |
VOOZH | about |
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 :
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:
Output:
[1] "Identity Matrix" [,1] [,2] [,3] [1,] 1 0 0 [2,] 0 1 0 [3,] 0 0 1
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:
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
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 :
Example:
We initially create a matrix of 0's and then the diagonals are assigned 1's using the diag() method defined earlier.
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