% Second example of the Kronecker model as used in section 4.2.2 where it uses the 
% the Rtx and Rrx matrix either side.
% Tim Brown, January 2012

N = 1000; % Arbritrary number of samples
ntx = 4;
nrx = 4;
R_tx = [1 0.6 0.5 0.2; % Example transmit correlation matrix, for 4x4 channel
        0.6 1 0.45 0.3;
        0.5 0.45 1 0.1;
        0.2 0.3 0.1 1];
R_rx = [1 0.44 0.42 0.3; % Example receive correlation matrix, for 4x4 channel
        0.44 1 0.41 0.23;
        0.42 0.41 1 0.13;
        0.3 0.23 0.13 1];

% Make iid Rayleigh distributed matrix
H_iid = (randn(nrx, ntx, N) + j * randn(nrx, ntx, N))/sqrt(2);    
    
% Create Kronecker correlated channel H
H_kron = zeros(ntx,nrx,N);
for nn = 1:N
    H_kron(:,:,nn) = chol(R_rx)*squeeze(H_iid(:,:,nn))*chol(R_tx).';
end

% Compare the eigen distributions to show the effect of correlation on the
% channel
S_iid = zeros(ntx, nrx, N);
S_kron = zeros(ntx, nrx, N);
for nn = 1:N
    [Uiid S_iid(:,:,nn) Viid] = svd(squeeze(H_iid(:,:,nn)));
    [Ukron S_kron(:,:,nn) Vkron] = svd(squeeze(H_kron(:,:,nn)));
end

% Generate histogram/probability density for singular values
bins_S_dB = [-30:1:20];
bins_S = 10.^(bins_S_dB./20);
pdf_s1iid = hist(abs(squeeze(S_iid(1,1,:))),bins_S);
pdf_s2iid = hist(abs(squeeze(S_iid(2,2,:))),bins_S);
pdf_s3iid = hist(abs(squeeze(S_iid(3,3,:))),bins_S);
pdf_s4iid = hist(abs(squeeze(S_iid(4,4,:))),bins_S);
pdf_s1kron = hist(abs(squeeze(S_kron(1,1,:))),bins_S);
pdf_s2kron = hist(abs(squeeze(S_kron(2,2,:))),bins_S);
pdf_s3kron = hist(abs(squeeze(S_kron(3,3,:))),bins_S);
pdf_s4kron = hist(abs(squeeze(S_kron(4,4,:))),bins_S);

% Convert histograms to cumulative distributions
NBins = length(bins_S);
CDF_s1iid = zeros(1,NBins);
CDF_s2iid = zeros(1,NBins);
CDF_s3iid = zeros(1,NBins);
CDF_s4iid = zeros(1,NBins);
CDF_s1kron = zeros(1,NBins);
CDF_s2kron = zeros(1,NBins);
CDF_s3kron = zeros(1,NBins);
CDF_s4kron = zeros(1,NBins);

for nb = 1:NBins
    CDF_s1iid(1,nb) = sum(squeeze(pdf_s1iid(1,1:nb)));
    CDF_s2iid(1,nb) = sum(squeeze(pdf_s2iid(1,1:nb)));
    CDF_s3iid(1,nb) = sum(squeeze(pdf_s3iid(1,1:nb)));
    CDF_s4iid(1,nb) = sum(squeeze(pdf_s4iid(1,1:nb)));
    CDF_s1kron(1,nb) = sum(squeeze(pdf_s1kron(1,1:nb)));
    CDF_s2kron(1,nb) = sum(squeeze(pdf_s2kron(1,1:nb)));
    CDF_s3kron(1,nb) = sum(squeeze(pdf_s3kron(1,1:nb)));
    CDF_s4kron(1,nb) = sum(squeeze(pdf_s4kron(1,1:nb)));
end

figure
semilogy(bins_S_dB,CDF_s1iid,'b-',bins_S_dB,CDF_s1kron,'g:',bins_S_dB,CDF_s2iid,'b-',bins_S_dB,CDF_s3iid,'b-', ...
         bins_S_dB,CDF_s4iid,'b-',bins_S_dB,CDF_s2kron,'g:',bins_S_dB,CDF_s3kron,'g:',bins_S_dB,CDF_s4kron,'g:')
set(gca,'FontSize',10)
set(gcf,'color','white')
ylabel('Cumulative Distribution (%)')
xlabel('Eigenvalue Magnitude (dB)')
legend('i.i.d Rayleigh','Kronecker')