%does a permutation analysis. Output is a histogram of mean differences and
%the upper and lower bounds of the 95% confidence interval. If the actual
%mean difference is outside of that interval the groups are significantly
%different. Should work for any data set with two groups. 

clear all
load PermutationData.mat %this data set is posted on the matlab site; 
%you could use any data with this script as long as the condition 
%is in column 2, there are two groups, and one is labeled "1" (they don't
%need to be equal)

%first get the actual mean difference:
n=1;
m=1;
for j=1:length(PermutationData)
        if PermutationData(j, 2)==1
            condition1(n)=PermutationData(j); 
            n=n+1;
        else
            condition0(m)=PermutationData(j);
            m=m+1;
        end
end
ActualDiff = mean(condition1)-mean(condition0) %output actual diff to CW

%Now do the resampling:
numResamp=1000; %Can play around with this number, but 1000 seems to be sufficient. . .
nullDist(numResamp, 1)=zeros; %make a matrix for the sampling distribution of mean differences
conditionLabelVector=PermutationData(:,2); 

for i=1:numResamp
    n=1;
    m=1;
    ShuffleLabels = shuffle(conditionLabelVector);
    %arbitrarily shuffle the condition labels
    for j=1:length(conditionLabelVector)
        if ShuffleLabels(j)==1
            condition1(n)=PermutationData(j); 
            n=n+1;
        else
            condition0(m)=PermutationData(j);
            m=m+1;
        end
    end
    nullDist(i) = mean(condition1)-mean(condition0); %add mean diff to sampling dist
end
%output histogram and CI to screen.
hist(nullDist)
UpperCIbound = quantile(nullDist, 0.975)
LowerCIbound = quantile(nullDist, 0.025)