# How to define JuMP expressions using a loop

Hi, I am trying to incorporate an expression into Julia using JuMP. Now I have been able to do this using MATLAB, but decided to switch to Julia for specific purposes. However based on the documentation provided for using JuMP, I am having some issues with the expressions.

I am dealing with a problem over a 24 hour period with 1hr intervals for some n battery devices. However, I need to initialize its capacity associated with this device in the first hour and then update it using and optimization variable (amount it charges and discharges by) after every hour.

So I have come up with something like this and just want to know if this makes sense:

``````BatteryCap = Array{Float64}(undef, nHours, n)
for j = 1:n
for k = 1:nHours
if k = 1
BatteryCap[k, j] = initialCapacity[j]
else
BatteryCap[k, j] = @expression(model, BatteryCap[(k-1), j] + Charging[k, j] - Discharging[k, j])
end
end
end
``````

Where Charging and Discharging are optimization variables which the solver would solve for.
For reference purposes, this is what I used in MATLAB:

``````%Update the Energy Capacity of the Storage
Capacity = optimexpr(nHours,num_of_storage);

for jj = 1:n
for kk = 1:nHours

if kk == 1

%Initialise the capacity at Hour = 1 to 50% of Storage Capacity
Capacity(kk,jj) = InitStorage_Capacity(1, jj);

else

Capacity(kk,jj) = Capacity((kk-1), jj) - (Discharging(kk, jj)) +Charging(kk, jj);

end

end
end
``````
1 Like

This is a reasonable way to initialize this. The only thing to change is that you should initialize `BatteryCap = Array{AffExpr,2}(undef, nHours, n)`. (Linear JuMP expressions are type `AffExpr`, not `Float64`.)

The other option is to write it as something like

``````@expression(
model,
BatteryCap[k = 1:nHours, j = 1:n],
initialCapacity[j] + sum(Charging[i, j] - Discharging[i, j] for i = 2:k)
)
``````
4 Likes