% hCalculatePrecodingMatrix Calculate PDSCH precoding matrix W 
%   W = hCalculatePrecodingMatrix(ENB,FADINGCHANNEL) calculates the PDSCH
%   precoding matrix W for a given ENB structure and propagation channel
%   FADINGCHANNEL configuration structure. The steps followed are:
%   * Get a perfect channel estimate for the considered subframe
%   * Average in time and frequency to obtain a channel estimate per
%   resource block (RB)
%   * Average the channel estimates for all the allocated RBs
%   * Calculate the singular value decomposition and extract the first
%   NLayers columns to obtain the precoding vector:

%   Copyright 2016 The MathWorks, Inc.

function  W = hCalculatePrecodingMatrix(enb, fadingChannel)

    % Obtain number of transmit and receive antennas
    nrxants = fadingChannel.NRxAnts;
    ntxants = size(enb.PDSCH.W,2);    
            
    % Get a perfect channel estimate.
    chest = lteDLPerfectChannelEstimate(enb,fadingChannel,[0 0],ntxants);
    % average over time 
    chestavgtime = mean(chest,2);
    % remove singleton dimension (2nd dim), do not use squeeze, it causes
    % problems for single rx antenna cases
    chestavgtime = permute(chestavgtime,[1 3 4 2]); 

    % Get an estimate per RB, average in frequency over 12 subcarriers
    kernel = ones(1,12);
    nsubcarriers = size(chestavgtime,1);
    chestavgRB = zeros(nsubcarriers/12,size(chestavgtime,2),size(chestavgtime,3));
    for nrx = 1:nrxants
        for ntx = 1:ntxants
            convout = conv(chestavgtime(:,nrx,ntx),kernel)/12;
            chestavgRB(:,nrx,ntx) = convout(12:12:end);
        end
    end

    % Get a single channel matrix for all allocated RBs (mean of all ch
    % matrices)
    tmp = permute(chestavgRB, [2 3 1]); % third dim is now RB number
    H = mean(tmp(:,:,enb.PDSCH.PRBSet+1),3); % mean over 3rd dimension
    
    % SVD decomposition to obtain precoding vector V
    [~,~,V] = svd(H,'econ');
    % Extract NLayers from V to form W
    W = V(:,1:enb.PDSCH.NLayers).'; % beamforming matrix from channel svd decomposition

end

