%hvbw2ff Video bandwidth to forgetting factor for exponential averaging
%   ALPHA = hvbw2ff(VBW,FS) converts the video bandwidth VBW in Hz for a
%   given sampling frequency FS (in Hz) to the equivalent forgetting factor
%   ALPHA for exponential averaging.
%
%   % Example: Configure a spectrum analyzer with a resolution bandwidth of
%   % 100kHz and a video bandwidth of 30kHz
%   fs = 30e6;
%   rbw = 100e3; % resolution bandwidth
%   vbw = 30e3;  % video bandwidth
%   alpha = hvbw2ff(vbw,fs); % forgetting factor
%   spectrumAnalyzer = dsp.SpectrumAnalyzer;
%   spectrumAnalyzer.SampleRate = fs;
%   spectrumAnalyzer.RBWSource = 'Property';
%   spectrumAnalyzer.RBW = rbw;
%   spectrumAnalyzer.AveragingMethod = 'Exponential';
%   spectrumAnalyzer.ForgettingFactor = alpha;
%   N = 10e3;
%   noisySignal = (sin(2*pi*1.1e6*(0:(N-1))/fs).')+0.001*randn(N,1);
%   spectrumAnalyzer(noisySignal);
%   release(spectrumAnalyzer)

%   Copyright 2020 The MathWorks, Inc.

function alpha = hvbw2ff(vbw,Fs)

    % Compute normalized 3dB frequency
    wc = 2*pi*vbw/Fs;

    % Solve for alpha
    % |H(e^(jwc))|^2 = (1-a)/(1-a*exp(-1j*wc))*(1-a)/(1-a*exp(1j*wc)) = 1/2
    % (1-a)^2/(1-2*a*cos(w) + a^2) = 1/2
    % a^2 - 2*a*(2-cos(wc)) + 1 = 0
    r = roots([1 -2*(2-cos(wc)) 1]);
    alpha = r((r<1) & (r >=0));
end
