The diag()
function in R simply creates a diagonal matrix.
The syntax of the diag()
function is given below:
diag(x, nrow, ncol)
The diag()
function takes the following parameter values:
x
: This is the value that makes the diagonal elements.nrow
, ncol
: These represent the number of rows and columns that the output matrix should have.The diag()
function returns a diagonal matrix.
A diagonal matrix is a matrix that has non-zero elements in the diagonal.
# creating the diagonal elementx <- 2# creating the number of rows the output matrix should havenrow <- 4# creating the number of column the output matrix should havencol <- 3# calling the diag() functionmymatrix <- diag(x, nrow, ncol)# printing the matrixmymatrix
x
.nrow
.ncol
.diag()
function on the given variables. The result is assigned to a variable mymatrix
.mymatrix
.