%scaleDelaysAndKFactor scaling of delays and K-factor for LOS channel models
%   TR 38.901 Section 7.7.3 Scaling of delays 
%   TR 38.901 Section 7.7.6 K-factor for LOS channel models

%#codegen
%#ok<*EMCA>

%    Copyright 2016-2018 The MathWorks, Inc.

function pdp = scaleDelaysAndKFactor(pdp,desiredKFactor,desiredDelaySpread)

    % named column subscripts
    [delay,power] = wireless.internal.channelmodels.namedDelayProfileColumns();
    
    % if desired K-factor is not NaN, apply K-factor scaling
    if (~isnan(desiredKFactor))
        
        K_desired = desiredKFactor;
        
        K_model = pdp(1,power) - 10*log10(sum(10.^(pdp(2:end,power)/10)));

        % scale the power of all taps excluding the 1st tap
        pdp(2:end,power) = pdp(2:end,power) - K_desired + K_model;
            
        % calculate the RMS delay spread after the K-factor adjustment
        tau_rms = calculateRMSDelaySpread(pdp);
        
        % normalise the delay spread
        pdp(:,delay) = pdp(:,delay) / tau_rms;
        
    end

    % scale delays according to desired delay spread, Section 7.7.3
    pdp(:,delay) = pdp(:,delay) * desiredDelaySpread;
    
end

function tau_rms = calculateRMSDelaySpread(pdp)

    % named column subscripts
    [delay,power] = wireless.internal.channelmodels.namedDelayProfileColumns();
    
    P = 10.^(pdp(:,power)/10);
    tau = pdp(:,delay);

    tau_rms = weightedRMS(tau,P);

end

function rms = weightedRMS(x,P)

    m1 = sum(P.*x)/sum(P);
    m2 = sum(P.*x.^2)/sum(P);

    rms = sqrt(m2 - m1^2);
    
end
