In my Julia optimisation model, I have a variable A which is a 5x5x5 array. Then A[:,:,1] is a matrix. In my model, I wish to calculate the sum of the column vectors of A[:,:,1]. Here is my code:
I = 1:5; J = 1:5; K = 1:5;
m = Model(HiGHS.Optimizer)
@variable(m, A[i in I, j in J, t in K] >= 0)
sum(A[:,:,1],dims = 2)
However, this gives me an error:
No method is implemented for reducing index range of type UnitRange{Int64}. Please implement reduced_index for this index type or report this as an issue.
How can I fix this error? The code works if I write
@variable(m, A[i in 1:5, j in 1:5, t in 1:5] >= 0)
but in my model, the indices I, J and K are given as an input to a function, so I cannot specify them like that.
CodePudding user response:
A[:,:,1]
yields a 2-dimensional DenseAxisArray
. You should do collect
on it to be able to aggregate via sum(..., dims=...)
. Hence you need to do:
julia> sum(collect(A[:,:,1]),dims = 2)
5×1 Matrix{AffExpr}:
A[1,1,1] A[1,2,1] A[1,3,1] A[1,4,1] A[1,5,1]
A[2,1,1] A[2,2,1] A[2,3,1] A[2,4,1] A[2,5,1]
A[3,1,1] A[3,2,1] A[3,3,1] A[3,4,1] A[3,5,1]
A[4,1,1] A[4,2,1] A[4,3,1] A[4,4,1] A[4,5,1]
A[5,1,1] A[5,2,1] A[5,3,1] A[5,4,1] A[5,5,1]
Please also note that your variable definition can be shortened to @variable(m, A[I, J, K] >= 0)