MethodError: no method matching getindex(::VariableRef, ::Int64)

Hi,

I’m using JuMP to solve my optimization problem. Following is a part of the formulation and its causing the methoderror.

for t in 1:tp
for j in 1:nt
c10= @constraint(p, LT[j][t] - (l[j] * Z[j][t]) == 0)
set_name(c10, “LTConstraint_[$j],[$t]”)
end
end

The variables are defined as follows:
@variable(p, Z[j in 1:nt, t in 1:tp] >=0, Int)
@variable(p, LT[j in 1:nt, t in 1:tp] >=0, Int)

and l[j] is a one dimensional array; l =[1,6,4,3,1,10,8,2,8,5,5,5,1,4]

The constraint c10 gives me the error: MethodError: no method matching getindex(::VariableRef, ::Int64)
I’m not sure what’s causing the error. Could anyone please help me understand what is causing the error.

Any help is deeply appreciated. Thanks in Advance!!

I would guess that LT[j][t] and Z[j][t] should instead be LT[j, t] and Z[j, t]. Otherwise you are getting a VariableRef from your matrix and then trying to index the variable.

Please, if possible use triple backticks to quote your code next time. When using triple backticks:

```
for t in 1:tp
for j in 1:nt
c10= @constraint(p, LT[j][t] - (l[j] * Z[j][t]) == 0)
set_name(c10, “LTConstraint_[$j],[$t]”)
end
end
```

becomes

for t in 1:tp
    for j in 1:nt
        c10= @constraint(p, LT[j][t] - (l[j] * Z[j][t]) == 0)
        set_name(c10, "LTConstraint_[$j],[$t]")
    end
end

What is more legible.

2 Likes

Thank you @henrique_becker for getting back to me. It did solve the error. How ever, I do have one other error after making the suggested change. Here the indices of variables are separated by comma but I still get a method matching error. Could you please help me with this one as well.

MethodError: no method matching -(::VariableRef, ::Array{Int64,1})

for t in 1:tp
	for i in 1:NJ[t]
	 		c2= @constraint(p, B[t,i,1] - nums[t,i] <= 0)
	 		set_name(c2, "InitConstraint_[$i],[$t]")
	end
end

nums[t,i] is a 2D array.

tp = 3
NJ = [7,5,8]
nums = [[13,2,21,16,11,2,5], [29,30,26,28,8], [8,5,16,130,5,13,30,4]]

Also, sorry about the previous format of the code.
Thank you in advance!!

The way you are declaring nums make it an array of arrays and not a matrix, so for nums the correct is nums[t][i]. I recommend reading the arrays section of the manual, but as a basic rule:

  1. If your data is an Array{T, 2} (i.e., a matrix) then it is indexed with m[i, j], and it has a size N x M, in other words, some rows or columns cannot be smaller than other rows or columns.
  2. If your data is an Vector{Vector{T}} (or Array{Array{T, 1}, 1}), then it is an array of arrays (or vector of vectors) and is indexed with a[i][j] (just a[i] will return the inner vector, then you index the inner vector with [j] for the integer inside it). Each element of the outer vector is a vector, and of these inner vectors can have a different sizes.
1 Like

Thank you very much @Henrique_Becker for your help and suggestion!!