add an iirFIlter function to choose a filter

This commit is contained in:
Tikea TE 2025-04-16 14:42:42 +02:00
parent 9a25101c5d
commit 9d349a8d80
1 changed files with 60 additions and 0 deletions

60
iirFilter.m Normal file
View File

@ -0,0 +1,60 @@
function [signal_filtered, Z, P] = iirFilter(N, cutoffFreq, signal, samplingFreq, filterType)
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% function [signal_filtered, Z, P] = iirFilter(N, cutoffFreq, signal, samplingFreq, filterType)
% ex.: [signal_filtered, Z, P] = iirFilter(6, [5 20], x, 200, 1)
%
% Task:
% To create and apply an IIR filter (Butterworth or Chebyshev)
% Supports low-pass or band-pass depending on the cutoffFreq input.
%
% Inputs:
% -N: order of the filter
% -cutoffFreq: scalar (for low-pass) or 2-element vector [low high] for bandpass
% -signal: input signal to be filtered
% -samplingFreq: sampling frequency in Hz
% -filterType: 1 = Butterworth, 2 = Chebyshev type I
%
% Outputs:
% -signal_filtered: filtered signal
% -Z: filter zeros
% -P: filter poles
%
% Author: Tikea TE
% Date: 16/04/2025
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% Design the filter
if filterType == 1
if length(cutoffFreq) == 1
[b, a] = butter(N, cutoffFreq / (samplingFreq / 2), 'low');
elseif length(cutoffFreq) == 2
[b, a] = butter(N, cutoffFreq / (samplingFreq / 2), 'bandpass');
else
error('cutoffFreq must be scalar or 2-element vector');
end
elseif filterType == 2
Rp = 10; % ripple for Chebyshev filter
if length(cutoffFreq) == 1
[b, a] = cheby1(N, Rp, cutoffFreq / (samplingFreq / 2), 'low');
elseif length(cutoffFreq) == 2
[b, a] = cheby1(N, Rp, cutoffFreq / (samplingFreq / 2), 'bandpass');
else
error('cutoffFreq must be scalar or 2-element vector');
end
else
error('Filter type must be 1 (Butterworth) or 2 (Chebyshev)');
end
% Analyze zeros/poles
[Z, P] = zeroPole(a, b, 1);
% Show frequency response
figure;
freqz(b, a, N, samplingFreq);
title('Frequency response');
grid on;
% Apply filter to signal
signal_filtered = filter(b, a, signal);
end