To create diagonal matrices in R, you can use the diag()
function. This function can be used in various ways to create matrices with specified diagonal values, either from a single vector or by specifying dimensions and a value.
In this example,
vec
containing the values c(1, 2, 3, 4)
.diag()
function with vec
as the argument. This function takes the values in vec
and places them on the diagonal of a new matrix, with all off-diagonal elements set to zero.diagonal_matrix
.diagonal_matrix
to standard output to see the resulting diagonal matrix.vec <- c(1, 2, 3, 4)
diagonal_matrix <- diag(vec)
print(diagonal_matrix)
[,1] [,2] [,3] [,4] [1,] 1 0 0 0 [2,] 0 2 0 0 [3,] 0 0 3 0 [4,] 0 0 0 4
In this example,
diag()
function with a single integer argument 4
. This integer specifies the dimensions of the resulting square identity matrix.diag()
function creates a 4x4 identity matrix, with ones on the diagonal and zeros elsewhere.identity_matrix
.identity_matrix
to standard output to see the identity matrix.identity_matrix <- diag(4)
print(identity_matrix)
[,1] [,2] [,3] [,4] [1,] 1 0 0 0 [2,] 0 1 0 0 [3,] 0 0 1 0 [4,] 0 0 0 1
In this example,
diag()
function with two arguments: a scalar value 5
and an integer 3
. The scalar value specifies the value to be placed on the diagonal, and the integer specifies the dimensions of the resulting square matrix.diag()
function creates a 3x3 matrix with the value 5
on the diagonal and zeros elsewhere.custom_diagonal_matrix
.custom_diagonal_matrix
to standard output to see the resulting matrix.custom_diagonal_matrix <- diag(5, 3)
print(custom_diagonal_matrix)
[,1] [,2] [,3] [1,] 5 0 0 [2,] 0 5 0 [3,] 0 0 5
In this tutorial, we learned How to Create Diagonal Matrices in R language with well detailed examples.