%% Create Constraints in Loop
% Create constraints for an inventory model. The stock of goods at the start of each period is equal to the stock at the end of the previous period. During each period, the stock increases by buy and decreases by sell. The variable stock is the stock at the end of the period.

N = 12;
stock = optimvar('stock',N,1,'Type','integer','LowerBound',0);
buy = optimvar('buy',N,1,'Type','integer','LowerBound',0);
sell = optimvar('sell',N,1,'Type','integer','LowerBound',0);
initialstock = 100;

stockbalance = optimconstr(N,1);

for t = 1:N
    if t == 1
        enterstock = initialstock;
    else
        enterstock = stock(t-1);
    end
    stockbalance(t) = stock(t) == enterstock + buy(t) - sell(t);
end

show(stockbalance)

%
% Include the constraints in a problem.

prob = optimproblem;
prob.Constraints.stockbalance = stockbalance;

%
% Instead of using a loop, you can create the same constraints by using matrix operations on the variables.

tt = ones(N-1,1);
d = diag(tt,-1); % shift index by -1
stockbalance2 = stock == d*stock + buy - sell;
stockbalance2(1) = stock(1) == initialstock + buy(1) - sell(1);

%
% See that the new constraints are the same as the constraints in stockbalance:

show(stockbalance2)

%
% Creating constraints in a loop can be more time-consuming than creating constraints by matrix operations. However, you are less likely to create an erroneous constraint by using loops.
%
% Copyright 2012-2019 The MathWorks, Inc.