【问题标题】:ERROR attempt to access 30×26 Array{VariableRef,2} at index [1, 0]错误尝试访问索引 [1, 0] 处的 30×26 Array{VariableRef,2}
【发布时间】:2019-11-10 17:16:36
【问题描述】:

当我想根据要求将工人分配到不同的班次时,我遇到了问题。他们可以每天两班倒。

但是不知道为什么是数组问题,我是Julia新手

empleados=26;
turnos=30;
requerimiento=[3,4,1,1,2,2,4,3,1,3,3,1,2,4,2,4,3,2,1,2,2,2,2,2,2,3]
costo=28;

using JuMP
using Gurobi
m = Model(with_optimizer(Gurobi.Optimizer))

@variable(m, x[1:turnos,1:empleados]<=1,Bin)

@objective(m, Min, costo * sum(x))    

for i in 1:turnos+1,j in 1:empleados
    @constraint(m,x[i,j] + x[i,j-1] + x[i,j+1]  <= 2)
end
for i in 1:turnos+3,j in 1:empleados
    @constraint(m, x[i,j]+x[i,j-2]+x[i,j-3]+x[i,j+3]+x[i,j+2] <= 1) 
end
    @constraint(m, sum(x[i,:]) for i in i:turnos >=requerimiento[i])

***ERROR***
BoundsError: attempt to access 30×26 Array{VariableRef,2} at index [1, 0]

Stacktrace:
 [1] getindex(::Array{VariableRef,2}, ::Int64, ::Int64) at .\array.jl:729
 [2] macro expansion at C:\Users\DELL\.julia\packages\JuMP\MsUSY\src\macros.jl:390 [inlined]
 [3] top-level scope at .\In[103]:15

【问题讨论】:

    标签: arrays indexing julia scheduled-tasks julia-jump


    【解决方案1】:

    第一个错误出现在这一行:

    for i in 1:turnos+1,j in 1:empleados
        @constraint(m,x[i,j] + x[i,j-1] + x[i,j+1]  <= 2)
    end
    

    在 Julia 中,数组通常从 1 开始索引(查找基于 1 的索引)。这与python等其他语言不同。

    这意味着如果您的数组大小为 (30,26),则您只能在第一个维度使用 1 到 30 的索引,在第二个维度使用 1 到 26 的索引。

    您的变量x 的大小为30x26,但在您的循环中,您尝试调用元素x[1,0](因为您在询问x[i,j - 1] 并且j 从1 开始)。 一旦通过重新制定索引或范围来解决此问题,您将遇到x[i,j+1] 部分的另一个问题,因为您将尝试访问同样不存在的x[1,27]。 您还需要修复 i 的范围,该范围目前在第一个索引 (for i in 1:turnos + 1) 中从 1 到 31。这也会破坏您的代码,因为您的数组在第一维中只有 30 大小。

    最后,在你正在构建的最后一行

    @constraint(m, sum(x[i,:]) for i in i:turnos &gt;=requerimiento[i])

    这将产生错误,因为您要求 ii 转到另一个值,这没有意义。

    所以你只需要仔细注意你是如何迭代你的数组的。

    使这条线工作的一种方法是:

    for i in 1:turnos,j in 2:empleados-1
           @constraint(m,x[i,j] + x[i,j-1] + x[i,j+1]  <= 2)
    end
    

    但我不了解你的模型,所以我不知道这是否是你想要做的。我能给你的最好建议是使用简单的示例更好地熟悉official docs 上的索引。

    【讨论】:

    • 谢谢,我的模型正在尝试将工人分配到特定的班次。
    猜你喜欢
    • 1970-01-01
    • 2018-06-15
    • 1970-01-01
    • 2021-04-12
    • 2019-01-06
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-05-21
    相关资源
    最近更新 更多