Extracts the diagonal from a matrix or makes a vector into a diagonal matrix.

# S4 method for class 'Expression'
diag(x = 1, nrow, ncol)

Arguments

x

An Expression, vector, or square matrix.

nrow, ncol

(Optional) Dimensions for the result when x is not a matrix.

Value

An Expression representing the diagonal vector or matrix.

Examples

C <- Variable(3,3)
obj <- Maximize(C[1,3])
constraints <- list(diag(C) == 1, C[1,2] == 0.6, C[2,3] == -0.3, C == Variable(3,3, PSD = TRUE))
prob <- Problem(obj, constraints)
result <- solve(prob)
result$value
#> [1] 0.5831514
result$getValue(C)
#>           [,1] [,2]       [,3]
#> [1,] 1.0000000  0.6  0.5831514
#> [2,] 0.6000000  1.0 -0.3000000
#> [3,] 0.5831514 -0.3  1.0000000