Name - Harpreet Kour
Roll no. - 22BCE040
Assignment Part-II
MATLAB Code for analyzing the performance of LPF and HPF digital filters.
clear; close all; clc;
%% Filter Parameters
fs = 1000; % Sampling frequency in Hz
fc = 200; % Cutoff frequency in Hz
M = 50; % Filter order (filter length = M+1 = 51)
n = 0:M; % Discrete time index
wc = 2*pi*fc/fs; % Normalized cutoff frequency (rad/sample)
%% Design of Low Pass Filter (LPF)
% Compute the ideal (non-causal, centered) impulse response:
h_ideal = zeros(1, M+1);
for i = 1:length(n)
if n(i) - M/2 == 0
% Handle the singularity by evaluating the limit:
h_ideal(i) = wc/pi;
else
h_ideal(i) = sin(wc*(n(i)-M/2))/(pi*(n(i)-M/2));
end
end
% Apply a Hamming window to obtain a practical LPF:
w = hamming(M+1)'; % Transpose to align dimensions
h_LPF = h_ideal .* w;
%% Design of High Pass Filter (HPF) using Spectral Inversion
% Create a discrete-time unit impulse centered at n = M/2:
delta = zeros(1, M+1);
delta(M/2+1) = 1; % MATLAB indexing: center index = M/2 + 1
% Apply spectral inversion:
h_HPF = delta - h_LPF;
%% Frequency Response Analysis
% LPF Frequency Response
figure;
subplot(2,1,1);
[H_lpf, w_lpf] = freqz(h_LPF, 1, 1024, fs);
plot(w_lpf, 20*log10(abs(H_lpf)+eps)); % eps added to avoid log(0)
xlabel('Frequency (Hz)');
ylabel('Magnitude (dB)');
title('Low Pass Filter Frequency Response');
grid on;
% HPF Frequency Response
subplot(2,1,2);
[H_hpf, w_hpf] = freqz(h_HPF, 1, 1024, fs);
plot(w_hpf, 20*log10(abs(H_hpf)+eps));
xlabel('Frequency (Hz)');
ylabel('Magnitude (dB)');
title('High Pass Filter Frequency Response');
grid on;
%% Time-Domain Analysis with a Composite Signal
% Generate a composite signal: sum of a low frequency and a high frequency sinusoid
t = 0:1/fs:1; % 1 second of data
x = sin(2*pi*50*t) + sin(2*pi*300*t); % 50 Hz (should pass LPF), 300 Hz (should pass HPF)
% Filter the signal using the LPF and HPF:
y_LPF = filter(h_LPF, 1, x);
y_HPF = filter(h_HPF, 1, x);
% Plot the input and output signals:
figure;
subplot(3,1,1);
plot(t, x);
xlabel('Time (s)');
ylabel('Amplitude');
title('Input Signal (Composite)');
grid on;
subplot(3,1,2);
plot(t, y_LPF);
xlabel('Time (s)');
ylabel('Amplitude');
title('Output Signal: Low Pass Filter');
grid on;
subplot(3,1,3);
plot(t, y_HPF);
xlabel('Time (s)');
ylabel('Amplitude');
title('Output Signal: High Pass Filter');
grid on;