How to write a function that implements an LTI filter using Direct Form 2?

12 views (last 30 days)
msspendragon
msspendragon on 11 Dec 2021
Commented: Mathieu NOE on 17 Dec 2021
function y_n = iirFilt(x_n)
global a b M N w_state;
Having trouble implementing the IIR DF-2 filter
Arrays b = [b0, b1,b2, b3, ...bM] and a = [a0, a1, a2, ..., aN] contain the corresponding coefficients of the filter system
Trying to make is so that the function takes a single input sample, x(n), and outputs y(n), I need to add "for" loops to calculate w(n) = x(n) + sum_i=1:n [-a(i)*w(n-i)] and another to calculate current output y(n) = sum_j=0:M[b(j)*w(n-j)] but not exactly sure how.
so far I have
function y_n = iirFilt(x_n)
global a b M N w_state;
out_n = 0
w_state(1)= x_n - (w_state(2)*a(2)) - (w_state(3)*a(3));
out_n = (w_state(1)*b(1)) + (w_state(2)*b(2)) + (w_state(3)*b(3));
% CONTINUE IMPLEMENTING THE IIR DF-2 FILTER ...
%delete the following line and implement a proper filter
w_state(3) = w_state(2);
w_state(2) = w_state(1);
y_n = out_n;

Answers (1)

Mathieu NOE
Mathieu NOE on 13 Dec 2021
hello
see my example below
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% load signal
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%% data
[x,Fs] = audioread('test_voice_mono.wav');
[samples,channels] = size(x);
dt = 1/Fs;
time = (0:samples-1)*dt;
%% IIR filter recursive equation
c1 = 8;
c2 = 2;
c3 = 7;
b0 = 0.05 * c1;
b1 = 0.03 * c2;
b2 = 0.02 * c3;
a1 = 0.5;
a2 = 0.5;
% manual for loop coding IIR filter
y(1) = b0*x(1) + 0 + 0 + 0 + 0; % 1st iteration
y(2) = b0*x(2) + b1*x(1) + 0 + a1*y(1) + 0; % 2nd iteration
for k = 3:samples % for iteration # 3 and after
y(k) = b0*x(k) + b1*x(k-1) + b2*x(k-2) + a1*y(k-1) + a2*y(k-2);
end
figure(1)
plot(time,x,time,y)

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!

Translated by