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 : 

Similar Reads

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....

Method 2: Using diag(nrow) method

...

Method 3: Creating a matrix of zeros and then assigning diagonals to 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....