%rgen.m
%generate a data set with a specified level of correlation

%geneate two random samples with mean=0 and std=1
sampleSize = 25;
x = rand(sampleSize,1);
x = (x-mean(x))/std(x);
y = rand(sampleSize,1);
y = (y-mean(y))/std(y);

%introduce dessired degree of colinearity
rho = 0.5;
a = rho/sqrt(1-rho.^2);
y2 = (a*x) + y;

%bootstrap permutation test for correlation
nIterations = 5000
bsd = zeros(nIterations,1);
for i=1:nIterations
    scrambled_y = y(randperm(sampleSize));
    bsd(i) = corr(x,scrambled_y);
end

%compute product-moment correlation and plot bivariate distribution
rho2 = corr(x,y2);
exact_p = sum(bsd >= rho2)/nIterations;
figure(1), subplot(2,1,1), scatter(x,y2);
title(['Correlation = ',num2str(rho2)]);
%
%plot bootstrap permutation distribution
subplot(2,1,2), hist(bsd)

