function [iBest,minBill] = Cheapest(C,Inv,PO)
% C is an nSupplier-by-nProd cost array
% Inv is an nSupplier-by-nProd inventory array
% PO is a 1-by-nProd purchase order array
% If at least one warehouse has sufficient inventory, then
% iBest is the index of the warehouse that can most cheaply fill
% the order and minBill is the associated cost.
% If no warehouse has sufficient inventory, then iBest = 0 and
% minBill = inf.
[nSupplier,nProd]= size(C);
iBest= 0; minBill= inf;
for i = 1:nSupplier
iBill= iCost(i,C,PO);
if iBill < minBill && iCanDo(i,Inv,PO)
iBest= i;
minBill= iBill;
end
end

%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
function TheBill = iCost(i,C,PO)
% The cost when warehouse i fills
% the purchase order
nProd= length(PO);
TheBill= 0;
for j = 1:nProd
TheBill= TheBill + C(i,j)*PO(j);
end

%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
function DO = iCanDo(i,Inv,PO)
% DO is true if warehouse i can fill
% the purchase order. Otherwise, false
nProd= length(PO);
DO= true;
for j = 1:nProd
DO= DO && (Inv(i,j) >= PO(j));
end