How to use diag method In R Language
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:
R
# creating a diagonal matrix with # dimensions 3 x 3 diag_mat < - diag (3) # printing identity matrix print ( "Identity Matrix" ) print (diag_mat) |
Output:
[1] "Identity Matrix" [,1] [,2] [,3] [1,] 1 0 0 [2,] 0 1 0 [3,] 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 :