Avoiding for Loop in JuMP

Is it possible to avoid for loop for the code given below.

@expression(JSTEP, Inj[i=1:n, j=1:s], Pg[i,j] - Pdmax[i,j] + PD[i,j] - PC[i,j])
for i = 1:r
  f = from[i]
  t = to[i]
  for k =1:s
    Inj[f,k] = Inj[f,k] -f₀[i,k]
    Inj[t,k] = Inj[t,k] + f₀[i,k]
    for j =1:nm_new[i] 
      Inj[f,k] = Inj[f,k] - fnew[i,k,j]
      Inj[t,k] = Inj[t,k] + fnew[i,k,j]

@constraint(JSTEP, [i=1:n, j=1:s], Inj[i,j]==0) 

Why do you want to avoid it, because it is slow? If so, check out the performace tips on building expressions

Ok I will check the performance tips.

1 Like

I can’t run your code because you haven’t provided a reproducible example. But this might help point you in the right direction:

@expression(JSTEP, Inj[i=1:n, j=1:s], Pg[i,j] - Pdmax[i,j] + PD[i,j] - PC[i,j])
@expression(JSTEP, sum_fnew[i=1:r, k=1:s], sum(fnew[i,k,j] for j in nm_new[i]) + f₀[i,k])
for i in 1:r, k in 1:s
    add_to_expression!(JSTEP, Inj[from[i], k], -1, sum_fnew[i, k])
    add_to_expression!(JSTEP, Inj[to[i], k], sum_fnew[i, k])
@constraint(JSTEP, [i=1:n, j=1:s], Inj[i, j] == 0)