%% Create Equality Constraints in Loop
% Create equality 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 = optimeq(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 an optimization 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.

stockbalance2 = optimeq(12, 1);
t = 2:12;
stockbalance2(t) = stock(t) == stock(t-1) + buy(t) - sell(t);
stockbalance2(1) = stock(1) == initialstock + buy(1) - sell(1);

% Display the new constraints. Note that they are the same as the constraints in stockbalance.

show(stockbalance2)

% Creating constraints in a loop can be more time consuming than creating constraints by using matrix operations.
%
% Copyright 2019 The MathWorks, Inc.