%% Create Indexed Equalities in Loop
% Create indexed equalities for a problem that involves shipping goods between airports. First, create indices representing airports.

airports = ["LAX" "JFK" "ORD"];

% Create indices representing goods to be shipped from one airport to another.

goods = ["Electronics" "Foodstuffs" "Clothing" "Raw Materials"];

% Create an array giving the weight of each unit of the goods.

weights = [1 20 5 100];

% Create a variable array representing quantities of goods to be shipped from each airport to each other airport. quantities(airport1,airport2,goods) represents the quantity of goods being shipped from airport1 to airport2.

quantities = optimvar('quantities',airports,airports,goods,'LowerBound',0);

% Create an equality constraint that the sum of the weights of goods being shipped from each airport is equal to the sum of the weights of goods being shipped to the airport.

eq = optimeq(airports);
outweight = optimexpr(size(eq));
inweight = optimexpr(size(eq));
for i = 1:length(airports)
    temp = optimexpr;
    temp2 = optimexpr;
    for j = 1:length(airports)
        for k = 1:length(goods)
            temp = temp + quantities(i,j,k)*weights(k);
            temp2 = temp2 + quantities(j,i,k)*weights(k);
        end
    end
    outweight(i) = temp;
    inweight(i) = temp2;
    eq(i) = outweight(i) == inweight(i);
end

% Examine the equalities.

show(eq)

%
% To avoid the nested for loops, express the equalities using standard MATLAB® operators. Create the array of departing quantities by summing over the arrival airport indices. Squeeze the result to remove the singleton dimension.

departing = squeeze(sum(quantities,2));

% Calculate the weights of the departing quantities.

departweights = departing * weights';

% Similarly, calculate the weights of arriving quantities.

arriving = squeeze(sum(quantities,1));
arriveweights = arriving*weights';

% Create the constraints that the departing weights equal the arriving weights.

eq2 = departweights == arriveweights;

% Include the appropriate index names for the equalities by setting the IndexNames property.

eq2.IndexNames = {airports,{}};

% Display the new equalities. Note that they match the previous equalities, but are transposed vectors.

show(eq2)

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