function ssim = dismatrix_ssim(data)
% structural similarity index (SSIM)
% References -  Mehul P. Sampat. Complex Wavelet Structural Similarity: A New Image Similarity Index. 2009
%               Z. Wang. Image quality assessment: From error visibility  to structural similarity. 2004
% Input
%   data  -  voxels x subjid
% Output
%   ssim  -  subjid x subjid

C             = 10.^-6;
u             = mean(data,1);
datademean    = data - repmat(u,size(data,1),1);
sig2          = sum(datademean.^2,1)./size(data,1);
ssim          = zeros(size(data,2));
for i=1:size(data,2)
    ux        = mean(data(:,i));
    sigx2     = sum((data(:,i) - ux).^2)./size(data,1);
    sigxy     = sum(repmat((data(:,i)-ux),1,size(data,2)).*datademean,1)./size(data,1);
    ssim(i,:) = (2*ux*u+C).*(2*sigxy+C)./((ux.^2+u.^2+C).*(sigx2 + sig2+C));
    clear ux sigx2 sigxy
end

ssim = (ssim + ssim')/2;
ssim = 1-ssim;
end