# Identical diagonal elements

Suppose you have

``````using JuMP,Ipopt
model = Model(Ipopt.Optimizer)
n = 5
@variable(model, X[1:n, 1:n])
``````

What is the easiest way to impose that the elements of main diagonal of X are identical. No restriction on what they are, they just need to be identical. That is X[1,1] = X[2,2] = … = X[n,n]

Add n - 1 constraints of the form `X[1, 1] == X[i, i]`?

What if n =1000?

Of course you’d write the constraints in a loop

``````for i in 1:n
@constraint(model, X[1, 1] == X[i, i])
end
``````

Another option is to just replace the diagonal elements of `X` with `X[1, 1]`:

``````julia> using JuMP

julia> model = Model()
A JuMP Model
Feasibility problem with:
Variables: 0
Model mode: AUTOMATIC
CachingOptimizer state: NO_OPTIMIZER
Solver name: No optimizer attached.

julia> n = 5
5

julia> @variable(model, X[1:n, 1:n])
5×5 Matrix{VariableRef}:
X[1,1]  X[1,2]  X[1,3]  X[1,4]  X[1,5]
X[2,1]  X[2,2]  X[2,3]  X[2,4]  X[2,5]
X[3,1]  X[3,2]  X[3,3]  X[3,4]  X[3,5]
X[4,1]  X[4,2]  X[4,3]  X[4,4]  X[4,5]
X[5,1]  X[5,2]  X[5,3]  X[5,4]  X[5,5]

julia> for i in 2:n
delete(model, X[i, i])  # We don't need this variable
X[i, i] = X[1, 1]       # Replace the diagonals with X[1, 1]
end

julia> X
5×5 Matrix{VariableRef}:
X[1,1]  X[1,2]  X[1,3]  X[1,4]  X[1,5]
X[2,1]  X[1,1]  X[2,3]  X[2,4]  X[2,5]
X[3,1]  X[3,2]  X[1,1]  X[3,4]  X[3,5]
X[4,1]  X[4,2]  X[4,3]  X[1,1]  X[4,5]
X[5,1]  X[5,2]  X[5,3]  X[5,4]  X[1,1]
``````
1 Like