 # diag() function in R The diagonal matrix is a very important concept that greatly affects optimizing algorithms. In this article, we will introduce the diag() function in R – a function to manipulate matrices to get diagonal matrices.

## What is the diag() function in R?

The diag() function replaces or extracts the matrix’s diagonal or creates a diagonal matrix.

#### Syntax:

• diag(matrix): Return the diagonal of the matrix.
• diag(matrix) = vector: Replace the diagonal of the matrix with new values.
• diag(value, m, n): Create a matrix having m rows and n columns, and the main diagonal elements are equal to the value, while other elements are 0.

#### Parameters:

• matrix: An existing matrix
• vector: A vector containing new values for the diagonal
• value: Values for the diagonal
• m: Number of rows
• n: Number of columns

## How to use the diag() function?

### Use the diag() function to get the diagonal of the matrix

Look at the following example and see how to get the primary diagonal value of a matrix.

Code:

# Create a vector containing values for a matrix
vector = c(1, 0, 11, 6, 3, 15, 21, 13, 7)

# Create a 3 x 3 matrix from the vector
matrix = matrix(vector, nrow = 3, ncol =3)

cat("The matrix is:\n")
print(matrix)

cat("The diagonal of the matrix is:\n")
print(diag(matrix))

Result:

The matrix is:
[,1] [,2] [,3]
[1,]    1    6   21
[2,]    0    3   13
[3,]   11   15    7
The diagonal of the matrix is:
 1 3 7


### Use the diag() function to replace the diagonal of the matrix

In this example, we will replace the diagonal of an existing matrix with new values.

Code:

# Create a vector containing values for a matrix
vector = c(1, 9, 11, 6, 3, 15, 21, 13, 7)

# Create a 3 x 3 matrix from the vector
matrix = matrix(vector, nrow = 3, ncol =3)

cat("The initial matrix is:\n")
print(matrix)

# Replace the diagonal of the matrix with 0
diag(matrix) = c(0, 0, 0)

cat("The new matrix is:\n")
print(matrix)

Result:

The initial matrix is:
[,1] [,2] [,3]
[1,]    1    6   21
[2,]    9    3   13
[3,]   11   15    7
The new matrix is:
[,1] [,2] [,3]
[1,]    0    6   21
[2,]    9    0   13
[3,]   11   15    0

### Use the diag() function to create an mxn diagonal matrix

Finally, the diag() function can create a matrix size m x n with the defined values in the main diagonal while other values are equal to zero.

Code:

# Create a 3 x 3 matrix with all elements in the main diagonal equal to 1
matrix = diag(1, 3, 3)

cat("The matrix with the diagonal is equal to 1:")
print(matrix)

Result:

The matrix with the diagonal is equal to 1:
[,1] [,2] [,3]
[1,]    1    0    0
[2,]    0    1    0
[3,]    0    0    1

## Summary

In summary, the diag() provides methods to work with diagonal matrices. You can use this function to get the values of the diagonal, replace the values of the diagonal and create a new matrix with fixed values in the diagonal.

Maybe you are interested:

Posted in R