I am trying to get an array of constraints, but I keep getting different kinds of errors, and I don't know what I'm doing wrong.
data array is 77x9 (integer values)
foods is a column vector of size 77x1, a variable of array type
lower is a column vector of 9x1, an integer vector
I should have 9 constraints
Here is what I have,
model2 = Model()
@variable(model2, foods[i=1:77] >= 0) # Quantity of food
for i ∈ 1:9
for j ∈ 1:77
@constraint(model2, c2[i], sum(data[j][i]*foods[j])<=lower[i])
end
end
What you want to do is
@constraint(model2, data' * foods .<= lower)
Let's make a toy example:
julia> @variable(model2, foods[i=1:3] >= 0)
3-element Vector{VariableRef}:
foods[1]
foods[2]
foods[3]
julia> data = collect(reshape(1:12, 3, 4))
3×4 Matrix{Int64}:
1 4 7 10
2 5 8 11
3 6 9 12
julia> lower = rand(101:104, 4)
4-element Vector{Int64}:
104
102
102
102
For such case you can use just matrix multiplication:
julia> data' * foods
4-element Vector{AffExpr}:
foods[1] + 2 foods[2] + 3 foods[3]
4 foods[1] + 5 foods[2] + 6 foods[3]
7 foods[1] + 8 foods[2] + 9 foods[3]
10 foods[1] + 11 foods[2] + 12 foods[3]
Now adding the right hand side constraint (note that we vectorized the <=
operator:
julia> @constraint(model2, data' * foods .<= lower)
4-element Vector{ConstraintRef{Model, MathOptInterface.ConstraintIndex{MathOptInterface.ScalarAffineFunction{Float64}, MathOptInterface.LessThan{Float64}}, ScalarShape}}:
foods[1] + 2 foods[2] + 3 foods[3] <= 104.0
4 foods[1] + 5 foods[2] + 6 foods[3] <= 102.0
7 foods[1] + 8 foods[2] + 9 foods[3] <= 102.0
10 foods[1] + 11 foods[2] + 12 foods[3] <= 102.0