约束数组 Julia
Array of constraints Julia
我正在尝试获取一组约束,但我不断收到各种错误,而且我不知道自己做错了什么。
data 数组为 77x9(整数值)
foods是一个大小为77x1的列向量,数组类型的变量
lower是9x1的列向量,整数向量
我应该有 9 个约束条件
这是我的,
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
你想做的是
@constraint(model2, data' * foods .<= lower)
说明
让我们做一个玩具示例:
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
对于这种情况,您可以只使用矩阵乘法:
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]
现在添加右侧约束(请注意,我们向量化了 <=
运算符:
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
我正在尝试获取一组约束,但我不断收到各种错误,而且我不知道自己做错了什么。
data 数组为 77x9(整数值)
foods是一个大小为77x1的列向量,数组类型的变量
lower是9x1的列向量,整数向量
我应该有 9 个约束条件
这是我的,
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
你想做的是
@constraint(model2, data' * foods .<= lower)
说明
让我们做一个玩具示例:
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
对于这种情况,您可以只使用矩阵乘法:
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]
现在添加右侧约束(请注意,我们向量化了 <=
运算符:
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