%helperVBWtoFF Featured example helper function
%   ALPHA = helperVBWtoFF(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:
%   %   Check that the frequency response of an IIR filter with a forgetting
%   %   factor of alpha is -3dB at VBW Hz.
%
%   VBW = 30e3;
%   Fs = 1e6;
%   alpha = helperVBWtoFF(VBW,Fs);
%   b = 1-alpha;      % numerator coefficients
%   a = [1 -alpha];   % denominator coefficients
%   H = freqz(b,a,[0 VBW],Fs); % evaluate at 0 and VBW Hz
%   disp("|H|.^2 = " + string(10*log10(abs(H(2)).^2)) + "dB at VBW = " + string(VBW) + "Hz")
    
%   Copyright 2020 The MathWorks, Inc.

function alpha = helperVBWtoFF(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