How to Create the Identity Matrix in R (With Examples)


In linear algebra, the identity matrix is a square matrix with ones on the main diagonal and zeros everywhere else.

You can create the identity matrix in R by using one of the following three methods:

#create identity matrix using diag()
diag(5)

#create identity matrix using diag() with explicit nrow argument
diag(nrow=5)

#create identity matrix by creating matrix of zeros, then filling diagonal with ones
mat <- matrix(0, 5, 5)
diag(mat) <- 1

Each of these methods lead to the same result.

The following examples show how to use each of these methods in practice.

Example 1: Create Identity Matrix Using diag()

The following code shows how to use the diag() function to create an identity matrix with 5 rows and 5 columns:

#create 5x5 identity matrix
ident <- diag(5)

#view matrix
ident

     [,1] [,2] [,3] [,4] [,5]
[1,]    1    0    0    0    0
[2,]    0    1    0    0    0
[3,]    0    0    1    0    0
[4,]    0    0    0    1    0
[5,]    0    0    0    0    1

The result is a 5×5 square matrix with ones on the main diagonal and zeros everywhere else.

Example 2: Create Identity Matrix Using diag(nrow)

The following code shows how to use the diag(nrow) function to create a 5×5 identity matrix:

#create 5x5 identity matrix
ident <- diag(nrow=5)

#view matrix
ident

     [,1] [,2] [,3] [,4] [,5]
[1,]    1    0    0    0    0
[2,]    0    1    0    0    0
[3,]    0    0    1    0    0
[4,]    0    0    0    1    0
[5,]    0    0    0    0    1

Example 3: Create Identity Matrix in Two Steps

The following code shows how create a 5×5 identity matrix by first creating a 5×5 matrix with all zeros, then converting the main diagonal values to be ones:

#create 5x5 matrix with zeros in all positions
ident <- matrix(0, 5, 5)

#make diagonal values 1
diag(ident) <- 1

#view matrix
ident

     [,1] [,2] [,3] [,4] [,5]
[1,]    1    0    0    0    0
[2,]    0    1    0    0    0
[3,]    0    0    1    0    0
[4,]    0    0    0    1    0
[5,]    0    0    0    0    1

Notice that each of the three methods produce the exact same identity matrix.

Additional Resources

The following articles provide helpful introductions to the identity matrix:

Khan Academy: Introduction to the Identity Matrix
Wikipedia: A Comprehensive Explanation of the Identity Matrix

The following articles explain how to perform other common matrix operations in R:

How to Perform Matrix Multiplication in R
How to Perform Element-Wise Multiplication in R
How to Plot the Rows of a Matrix in R

Leave a Reply

Your email address will not be published.