function [iBest,minBill] = Cheapest(C,Inv,PO)
% C is an nFact-by-nProd cost array
% Inv is an nFact-by-nProd inventory array
% PO is a 1-by-nProd purchase order array
% If at least one factory has sufficient inventory, then
% iBest is the index of the factory that can most cheaply fill
% the order and minBill is the associated cost.
% If no factory has sufficient inventory, then iBest = 0 and
% minBill = inf.
[nFact,nProd] = size(C);
iBest = 0; minBill = inf;
for i=1:nFact
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 factory 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 factory 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