% cost and decision matrix for inv control problem pg 25 prob 1 in Denardo

clc
clear
clc
%set up the model parameters
DD=0;
%**********************
DD= [2 1 1 0
    ];
maxhold=2;
maxprod=2;
startinv=1;
endinv=1;
%************************
cc=0;
ccc=0;
cccc=0;
xx=0;
xxx=0;
xxxx=0;
a=0;
sizeDD=size(DD);
nstate= maxhold+1;
nstage= sizeDD(1,2)+1;
cc=zeros(nstage*nstate, nstage*nstate);
xx=zeros(nstage*nstate, nstage*nstate);
countr=1;
countc=nstate+1;

D=DD;
sizeD=size(D);
for k=1:1:sizeD(1,2)
    
    D=D(1,k)

for i= 0:1:maxhold
    for j=0:1:maxhold
        x=j-i+D;
        if x>0 & x<=maxprod
            if i==0 & x==1
                c=17;
            elseif i==0 & x==2
                c=20;
            elseif i==1 & x==1
                c=20;
            elseif i==1 & x==2
                c=23;
            elseif i==2 & x==1
                c=24;
            elseif i==2 & x==2
            c=27;
            end
            
        elseif x==0
            if i==0
                c=10;
            elseif i==1
                c=13;
            elseif i==2
                c=17;
            end
                if c==0 % arc exists
                c=0.0001;
                end
        elseif x<0
            c=100; % infeasible arcs
        elseif x>maxprod
            c=100; % infeasible arcs
        end
       
        a(i+1,j+1)=c;
        xx(countr,countc)=x;
        cc(countr,countc)=c;
        countc=countc+1;
    end
    countr=countr+1;
    countc=countc-nstate;
end
countc=countc+nstate;
     D= DD;       
    a
end
cc;
xx;
 

 % the following code will trim c and X  to have one source and one
 % sink only
 %for inv control problem
 %one source
 c=cc;
 X=xx;
sizec=size(c);
sizex=size(X);
for i=1:1:sizec(1,2)
c2(1,i)=c(startinv+1,i);
X2(1,i)=X(startinv+1,i);
end
rowc=2;
 for i=nstate+1:1:sizec(1,1)
    for j= 1:1:sizec(1,2)
    c2(rowc,j)=c(i,j);
    X2(rowc,j)=X(i,j);
    end
 rowc=rowc+1;
 end
 
%one sink
sizec2=size(c2);
sizeX2=size(X2);
colc=1;
for i=1:1:(nstate*(nstage-1))
     for j= 1:1:sizec2(1,1)
     c3(j,colc)=c2(j,i);
     X3(j,colc)=X2(j,i);
     end
colc=colc+1;
end
for i=1:1:sizec2(1,1)
c3(i,1+(nstate*(nstage-1)))=c2(i,((nstage*nstate)-nstate+endinv+1));
X3(i,1+(nstate*(nstage-1)))=X2(i,((nstage*nstate)-nstate+endinv+1));
end

%the following will trim the zeros in the first few colums and the last few
%rows.Keep only first column and last row with all zeros
cc=c3; 
xx=X3;
cccc=0;
 sizecc=size(cc);
 ccc= cc(1:sizecc(1,1)-nstate+1,:);
 cccc= ccc(:, nstate:sizecc(1,2));
 cccc;
 
 xxxx=0;
 sizexx=size(xx);
 xxx= xx(1:sizexx(1,1)-nstate+1,:);
 xxxx= xxx(:, nstate:sizexx(1,2));
 xxxx;
 
 c=cccc % c has the correct rows and columns with one source and sink
 X=xxxx % X has the correct rows and columns with one source and sink
 
 
 % these files are written in the same folder where this code is saved.
 xlswrite('costinv1.xlsx',c)
 xlswrite('decisioninv1.xlsx',X)
 
