In R, you can create an identity matrix using the diag()
function. This function creates a diagonal matrix with specified dimensions, where the diagonal elements are all 1s and off-diagonal elements are 0s.
In this example,
diag()
function to create a 3x3 identity matrix. The argument nrow
specifies the number of rows in the matrix.identity_mat
.identity_mat
to the console to verify the creation of the identity matrix.identity_mat <- diag(3)
print(identity_mat)
[,1] [,2] [,3] [1,] 1 0 0 [2,] 0 1 0 [3,] 0 0 1
In this example,
diag()
function to create a 4x4 identity matrix. The argument nrow
specifies the number of rows in the matrix.identity_mat
.identity_mat
to the console to verify the creation of the identity matrix.identity_mat <- diag(4)
print(identity_mat)
[,1] [,2] [,3] [,4] [1,] 1 0 0 0 [2,] 0 1 0 0 [3,] 0 0 1 0 [4,] 0 0 0 1
In this tutorial, we learned How to Create Identity Matrix in R language with well detailed examples.