 function [n_all, Chisq_1] = W_comp(Wdist,West,N) % Distance based W matrix; MT estimated W matrix
U_W=triu(Wdist,1)+1; % Distance matrix (1s on diagonal)
fill_W=(-1)*tril(ones(N),0);
f_W=fill_W+U_W;
r_W=reshape(f_W,N^2,1);
r_W=r_W';
B_W=zeros(1,1);
r_W1 = r_W(:,~all(r_W == repmat(B_W,1,size(r_W,2)),1));
r_W1=r_W1';
r_W1=r_W1-1;

U_What=triu(West,1)+1; % Choice of empirical matrix to enter (1s on diagonal)
f_What=fill_W+U_What;
r_What=reshape(f_What,N^2,1);
r_What=r_What';
r_W1hat = r_What(:,~all(r_What == repmat(B_W,1,size(r_What,2)),1));
r_W1hat=r_W1hat';
r_W1hat=r_W1hat-1;

% Contigency Table
n_11=sum(r_W1.*r_W1hat);
n_00=sum((1-r_W1).*(1-r_W1hat));
n_10= sum(r_W1.*(1-r_W1hat));
n_01= sum((1-r_W1).*r_W1hat);
n_all=[n_11 n_01; n_10 n_00];

% Chi-squared statistic
el1=n_11^2/((n_10+n_11)*(n_01+n_11));
el2=n_10^2/((n_10+n_11)*(n_00+n_10));
el3=n_01^2/((n_00+n_01)*(n_01+n_11));
el4=n_00^2/((n_00+n_01)*(n_00+n_10));
Chisq_1 =(n_11+n_01+n_10+n_00)*((el1+el2+el3+el4)-1);
