Reputation: 57
I essentially have a whole lot of coefficients that i want to pair up with variables of another matrix, so as to save time in writing out constraints.
Something like this:
In Julia, I ideally want to be able to say something like this:
@variable(model, x[1:9])
A = collect[1:9]
@constraint(model, A =? x[1:9])
Much obliged!
Upvotes: 1
Views: 159
Reputation: 20248
Are you looking for the element-wise product of two arrays? If so, it is denoted .*
, following the widely used convention in Julia, that .
denotes "broadcasting", i.e. elementwise application of a function to a collection:
julia> x = 1 .+ 0.1*rand(3,3)
3×3 Array{Float64,2}:
1.01642 1.01822 1.08074
1.01375 1.01617 1.04618
1.06083 1.09773 1.07278
julia> A = reshape(1:9, 3, 3)
3×3 reshape(::UnitRange{Int64}, 3, 3) with eltype Int64:
1 4 7
2 5 8
3 6 9
julia> A.*x
3×3 Array{Float64,2}:
1.01642 4.07288 7.56517
2.0275 5.08086 8.36943
3.18249 6.58637 9.65506
Note that broadcasting is a very general technique, which you can use anywhere. And JuMP is no exception:
julia> using JuMP
julia> model = JuMP.Model()
A JuMP Model
Feasibility problem with:
Variables: 0
Model mode: AUTOMATIC
CachingOptimizer state: NO_OPTIMIZER
Solver name: No optimizer attached.
julia> @variable(model, x[1:3,1:3])
3×3 Array{VariableRef,2}:
x[1,1] x[1,2] x[1,3]
x[2,1] x[2,2] x[2,3]
x[3,1] x[3,2] x[3,3]
julia> A = reshape(1:9, 3, 3)
3×3 reshape(::UnitRange{Int64}, 3, 3) with eltype Int64:
1 4 7
2 5 8
3 6 9
# Note how both * and <= are broadcasted to be applied element-wise
julia> @constraint(model, con, A .* x .<= 1)
3×3 Array{ConstraintRef{Model,MathOptInterface.ConstraintIndex{MathOptInterface.ScalarAffineFunction{Float64},MathOptInterface.LessThan{Float64}},ScalarShape},2}:
x[1,1] ≤ 1.0 4 x[1,2] ≤ 1.0 7 x[1,3] ≤ 1.0
2 x[2,1] ≤ 1.0 5 x[2,2] ≤ 1.0 8 x[2,3] ≤ 1.0
3 x[3,1] ≤ 1.0 6 x[3,2] ≤ 1.0 9 x[3,3] ≤ 1.0
Upvotes: 4