clear all
close all
nsubjects = 20000; 
prevalence = 0.2; 
se1  =0.9; sp1   = 0.8;  %se/sp of test1
se20 =0.7; sp20  = 0.9;  %se/sp of test2 if test1=0
se21 =0.95; sp21 = 0.6;  %se/sp of test2 if test1=1

tests = [];
ss=[]; tp=0; fp=0; fn=0; tn=0;
for i = 1:nsubjects
   %simulate a subjest wp of disease equal to prevalence
   s = (rand < prevalence); 
   %test the subject
   test1=s*(rand < se1) + (1-s)*(rand>sp1); %test is 0 or 1
   if (test1 == 0)
       test2=s*(rand < se20) + (1-s)*(rand>sp20); 
   else
       test2=s*(rand < se21) + (1-s)*(rand>sp21); 
   end
   %test = test1*test2;          %for serial 
   test = (test1 + test2 > 0);  %for parallel
   ss=[ss s];                   %save subject's status
   tests = [tests test];        %save subject's test  
   %building the test table 
   tp = tp + test*s;          %true positives
   fp = fp + test*(1-s);      %false positives
   fn = fn + (1-test)*s;      %false negatives
   tn = tn + (1-test)*(1-s);  %true negatives
end
% estimate overall Se/Sp from the table
sens = tp/(tp+fn) 
spec = tn/(tn+fp)
