% Plot The Original Signal in Time and Frequency Domains
% Plot The Original Signal in Time and Frequency Domains
clc;
clear;
close all;
disp('Choose Filter Type:');
disp('1. Low Pass Filter');
disp('2. High Pass Filter');
disp('3. Band Pass Filter');
disp('4. Band Stop Filter');
filterChoice = input('Enter your choice: ');
f1 = 1000;
f2 = 6000;
f3 = 10000;
fs = 24000;
t = 0:1/fs:0.1;
x = 2*sin(2*pi*f1*t) + sin(2*pi*f2*t) + 4*sin(2*pi*f3*t);
% Plot the original signal in time and frequency domains
figure;
subplot(2, 1, 1);
plot(t, x);
title('Time Domain Signal');
xlabel('Time (s)');
ylabel('Amplitude');
X = abs(fft(x));
Nx = length(X);
fx = (0:Nx-1) * fs / Nx;
subplot(2, 1, 2);
plot(fx(1:floor(Nx/2)), X(1:floor(Nx/2)));
title('Frequency Domain Signal');
xlabel('Frequency (Hz)');
ylabel('Magnitude');
% Design the filter
M = 31; % Filter length
m = -(M-1)/2 : (M-1)/2;
switch filterChoice
case 1
% Low Pass Filter
fc = 5000; % Cut-off frequency
b = fir1(M-1, fc/(fs/2), 'low', rectwin(M));
filterType = 'Low Pass';
case 2
% High Pass Filter
fc = 5000; % Cut-off frequency
b = fir1(M-1, fc/(fs/2), 'high', rectwin(M));
filterType = 'High Pass';
case 3
% Band Pass Filter
fc1 = 3000; % Lower cut-off frequency
fc2 = 7000; % Upper cut-off frequency
b = fir1(M-1, [fc1 fc2]/(fs/2), 'bandpass', rectwin(M));
filterType = 'Band Pass';
case 4
% Band Stop Filter
fc1 = 3000; % Lower cut-off frequency
fc2 = 7000; % Upper cut-off frequency
b = fir1(M-1, [fc1 fc2]/(fs/2), 'stop', rectwin(M));
filterType = 'Band Stop';
otherwise
disp('Invalid filter choice');
return;
end
% Frequency response of the filter
[H, ff] = freqz(b, 1, 2048, fs);
absH = abs(H);
magH = 20*log10(absH);
phaseH = angle(H);
% Filter the signal
y = filter(b, 1, x);
% Plot filter magnitude and phase response
figure;
subplot(2, 1, 1);
plot(ff, magH);
title(['Magnitude Response - ' filterType ' Filter']);
xlabel('Frequency (Hz)');
ylabel('Magnitude (dB)');
grid on;
subplot(2, 1, 2);
plot(ff, phaseH);
title(['Phase Response - ' filterType ' Filter']);
xlabel('Frequency (Hz)');
ylabel('Phase (radians)');
grid on;
% Plot filtered signal in time and frequency domains
figure;
subplot(2, 1, 1);
plot(t, y);
title(['Filtered Signal in Time Domain - ' filterType ' Filter']);
xlabel('Time (s)');
ylabel('Amplitude');
Y = abs(fft(y));
Ny = length(Y);
fy = (0:Ny-1) * fs / Ny;
subplot(2, 1, 2);
plot(fy(1:floor(Ny/2)), Y(1:floor(Ny/2)));
title(['Filtered Signal in Frequency Domain - ' filterType ' Filter']);
xlabel('Frequency (Hz)');
ylabel('Magnitude');