% single_pole_iir_example.m
%
% https://tomroelandts.com/articles/low-pass-single-pole-iir-filter
%
setAxesDefaults

%% Gen signal
fs = 500;   % sampling freq
ts = 1/fs;  % sampling period
frq = 50;   % signal freq
K = fs;     % 1 second of data

k = 0:(K-1);
x = cos(2*pi*frq/fs*k);
% x = randn(K,1);

% x = [ones(1,20)];

%% filter params
% fc = 0.01;          % -3 dB cutoff frequency
% d = exp(-2*pi*fc);  % decay value

% tau = 0.9;
% d = exp(-ts/tau);    % decay value (pole)

d = 0.9;    % decay value (pole)
fc = -log(d)/(2*pi); % -3 dB cutoff frequency (approximation)
b = 1 - d;           % gain


% Apply filter
y = zeros(size(x,2),1);
y(1) = 0;  % Choose some initialization for y(1)
for n = 2:length(x)
    % y += b * (x - y)
    y(n) = y(n-1) + b*(x(n) - y(n-1));
end


ca
figure;
plot(k, x); hold on;
plot(k, y)
title(['Decay = ' num2str(d) ', -3 dB cutoff frequency {\itf_c} = ' num2str(fc) ' Hz'])
