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.
R
# 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
How to Create the Identity Matrix in R?
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 :