for k=1:n_sim for i=1:m %i is the month that components were produced nj = n; %nj is the number of working components at month j. pf = 1-exp(-r(i)); % pf is prob failing at month j given that working at j-1. j=i+1; while (nj~=0 && j<=m+m2) %while the number of working components is not 0 and j is less than the month of interest Ks(i,j) = simbinom(1,nj,pf); %simulate 1 value of #failures of working components nj = nj-Ks(i,j); %change number of working componets for the next month to #working month before - #failed this month j=j+1; end while j<=m+m2 %takes care of case when nj=0 before j