0% found this document useful (0 votes)
20 views60 pages

UI21CS66_DSP_Lab

The document outlines a series of tasks and experiments conducted in a Digital Signal Processing course at the Indian Institute of Information Technology Surat. It includes MATLAB implementations for various signal processing techniques such as Z-transform, DFT, IDFT, and convolution, along with code snippets and outputs for each task. The document serves as a comprehensive guide for students to understand and apply digital signal processing concepts through practical coding exercises.

Uploaded by

ui21ec63
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
20 views60 pages

UI21CS66_DSP_Lab

The document outlines a series of tasks and experiments conducted in a Digital Signal Processing course at the Indian Institute of Information Technology Surat. It includes MATLAB implementations for various signal processing techniques such as Z-transform, DFT, IDFT, and convolution, along with code snippets and outputs for each task. The document serves as a comprehensive guide for students to understand and apply digital signal processing concepts through practical coding exercises.

Uploaded by

ui21ec63
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 60

Indian Institute of Information Technology Surat

Digital Signal Processing(EC 503)

Submitted by

Biyawala Viral Deven(UI21CS66)

Course Faculty

Dr. Hemant Gokhlani


Dr. Sudeep Sharma

Department of Computer Science and Engineering


Indian Institute of Information Technology Surat
Gujarat-394190, India

August 2023
Index

Sr. Date Title Sign


No.
1. 31/7/23 To implement certain standard discrete time signals.
2. 7/8/23 Implement z-transform with and without using inbuilt
method and also find poles and zeroes of a z-function.

3. 14/8/23 To implement inverse Z-transform with and without using


inbuilt function in MATLAB.

4. 21/8/23 To implement DFT and IDFT using Direct method in MATLAB

5. 28/8/23 To perform circular convolution


1.by using inbuilt dft and idft function
2.by using user defined dft and idft functions
3.by using matrix multiplication technique
4.by using concentric circle method

6. 4/9/23 To implement DIT-FFT algorithm for calculating Fast fourier


transform.
7. 3/10/23 To implement DIF-FFT algorithm for calculating Fast fourier
transform.

8. 10/10/23 To study and plot the frequency response of digital system or


filter. Also calculate the cut-off frequencies and transfer
functions of low pass,high pass, band pass, and band stop
filters.
9. 17/10/23 To realize the digital system & filter using Direct
Form,Cascade Form and Parallel Form in matlab as well as
simulink.
10. 24/10/23 To implement linear phase characteristics of FIR discrete
digital filters using MATLAB
11. 16/11/23 To implement various window methods to obtain FIR filter
response from IIR signal using MATLAB.

12. 23/11/23 To implement IIR filter realisation using Bilinear


transformation and Impulse Invariance method.
LAB-1
TASK 1: Generation of continuous and discrete-time Step, Ramp
and Sinusoidal (1Hz and 3Hz) signals and plot them.

CODE:

clc;
close all;%Close all opened Graphs
t=-1:0.001:1;
l=(length(t));

for i=1:l
if(t(i)<0)
x(i)=0;
else
x(i)=1;
end
end

% Discrete Time Ramp Signal


plot(t,x,'m',LineWidth=1.5);
grid on;
axis([-1,1,-0.1,1.1])
xlabel('Time(t)');
ylabel('Amplitude')
title('Unit Step Signal')

n=-1:0.05:1;
N=length(n);
for i=1:N
if n(i)<0
y(i)=0;
else
y(i)=1;
end
end
figure;
stem(n,y,'b','LineWidth',0.2);
grid on;
axis([-1,1,-0.1,1.1]);
xlabel('Time(n)');
ylabel('Amplitude');
title('Unit Step Sequence');
% Continuous Time Ramp Signal
t=-1:0.05:1;
N=length(n);

for i=1:N
if t(i)<0
z(i)=0;
else
z(i)=t(i);
end
end
figure;
plot(t,z,'b','LineWidth',0.2);
grid on;
axis([-1,1,-0.1,1.1]);
xlabel('Time(t)');
ylabel('Amplitude');
title('Ramp Signal');

% Discrete Time Ramp Signal


n=-1:0.05:1;
N=length(n);
for i=1:N
if n(i)<0
w(i)=0;
else
w(i)=n(i);
end
end
figure;
stem(n,w,'b','LineWidth',0.2);
grid on;
axis([-1,1,-0.1,1.1]);
xlabel('Time(n)');
ylabel('Amplitude');
title('Ramp Sequence');

OUTPUT:
TASK 2: Perform addition, subtraction and multiplication on
Sinusoidal signals and plot the results.
CODE:
clc;
clear All;
close all;

t = -2:0.001:2;
f1=1;
f2=3;
pi=3.14;
x1=sin(2*pi*f1*t);
x2=sin(2*pi*f2*t);

% PLotting first Wave


figure;
plot(t,x1);
axis([-2,2,-2.1,2.1]);
grid on;
xlabel("Time");
ylabel("Amplitude");
title("Sine Wave(1Hz)");

% Plotting second wave


figure;
plot(t,x2);
axis([-2,2,-2.1,2.1]);
grid on;
xlabel("Time");
ylabel("Amplitude");
title("Sine Wave(3Hz)");

% Adding 2 Sine Waves


figure;
plot(t,x1+x2);
axis([-2,2,-2.1,2.1]);
grid on;
xlabel("Time");
ylabel("Amplitude");
legend('1 Hz','3 Hz')
title("sin1+sin2");

% Substracting 2 Sine Waves


figure;
plot(t,x1-x2);
axis([-2,2,-2.1,2.1]);
grid on;
xlabel("Time");
ylabel("Amplitude");
legend('1 Hz','3 Hz')
title("sin1-sin2");

% Multiplying 2 Sine Waves


figure;
plot(t,x1.*x2);
axis([-2,2,-2.1,2.1]);
grid on;
xlabel("Time");
ylabel("Amplitude");
legend('1 Hz','3 Hz')
title("sin1*sin2");

OUTPUT:
1) Sine wave with frequency = 1Hz

2) SINE WAVE FUNCTION WITH f=3Hz


3) ADDITION OF 2 SINE-WAVES

4) SUBTRACTION OF 2 SINE WAVES


5) PRODUCT OF 2 WAVES
TASK 3: Perform time shifting on the signals and plot the
results.

CODE:
% Time Shifting
figure;
plot(t,sin(2*pi*f1*(t)));
axis([-2,2,-2.1,2.1]);
grid on;
xlabel("Time");
ylabel("Amplitude");
title("Time Shifting");

% Time Shifting
figure;
plot(t,sin(2*pi*f1*(t+100)));
axis([-2,2,-2.1,2.1]);
grid on;
xlabel("Time");
ylabel("Amplitude");
title("Time Shifting");

OUTPUT:
1)ORIGINAL SINE WAVE
2)TIME SHIFTED SINE WAVE
TASK 4: Perform 4, 8 and 16 levels of digitization on sinusoidal
signals and plot them.
CODE:
t = -2:0.001:2;
f=1;
pi=3.14;
x1=sin(2*pi*f*t);

y2=floor(x1/0.5);
figure;
plot(t,y2/2);
axis([-2,2,-2.1,2.1]);
grid on;
xlabel("Time");
ylabel("Amplitude");
legend('1 Hz','3 Hz')
title("Sine Wave(4 Quantization Levels)");

y3=floor(x1/0.25);
figure;
plot(t,y3/4);
axis([-2,2,-2.1,2.1]);
grid on;
xlabel("Time");
ylabel("Amplitude");
legend('1 Hz','3 Hz')
title("Sine Wave(8 Quantization Levels)");

y4=floor(x1/0.125);
figure;
plot(t,y4/8);
axis([-2,2,-2.1,2.1]);
grid on;
xlabel("Time");
ylabel("Amplitude");
legend('1 Hz','3 Hz')
title("Sine Wave(16 Quantization Levels)");
OUTPUT:
1) SINE WAVE (4 QUANTIZATION LEVELS)

2) SINE WAVE (8 QUANTIZATION LEVELS)


3) SINE WAVE (16 QUANTIZATION LEVELS)

CONCLUSION:
Through this experiment, we came to know about the plotting of various analog
signals and the digitization of the same with variable step size.
LAB-2

TASK 1: To implement Z-transform in MATLAB with and without


inbuilt function.
CODE:
1. Without using Inbuilt function
% Without Using BuiltIn Function
clc; % Clear The Command Window
clear all; % Clear The Workspace
close all;

Ztrans(4,[1,2,3,4])
Ztrans(5,[4,3,1,2,9])
Ztrans(6,[3,5,7,9,10,12])
Ztrans(2,[2,9])
Ztrans(5,[1,2,5,3,4])

function res=Ztrans(s,xn)
n_min=0;
n_max=s-1;
syms k;
syms x;
syms z;
f(x,k)=x*(z^(-k));
m=1;
for n=n_min:n_max
xz(m)=f(xn(m),n);
m=m+1;
end
res=sum(xz);
end

2. With using Inbuilt function

clc;
clear all;
close all;

n = 0:10;
for i = 0:11
if i==0
ui(i+1)=1;
else
ui(i+1)=0;
end
end
syms z;
Z_transform = ztrans(ui,z);
disp(Z_transform)

f=[1 2 3 4];
Z_transform = ztrans(f,z);
disp(Z_transform)

syms n;
f=sin(n);
Z_transform = ztrans(f,z);
disp(Z_transform)

disp(ztrans(cos(n),z))

disp(ztrans([4,3,1,2],z))

OUTPUT:
a) Without using inbuilt function:
b) Using inbuilt function:
TASK 1: To implement Z-transform in MATLAB with and without
inbuilt function.

CODE :

z = tf('z');

H = z;
pzmap(H);

figure;
H = (z - 1) / (z + 1);
pzmap(H);

figure;
H = ((z - 1j)*(z + 1j)) / ((z - exp(1j*pi/4))*(z - exp(-1j*pi/4)));
pzmap(H);

figure;
H = ((z - 0.5 - 0.5j)*(z - 0.5 + 0.5j)) / ((z - 0.7 - 0.2j)*(z - 0.7 + 0.2j));
pzmap(H);

figure;
H = 1 / ((z - 0.9*exp(1j*pi/10))*(z - 0.9*exp(-1j*pi/10)));
pzmap(H);

OUTPUT:

1. H=z
2. H=(z-1)/(z+1)

3. H=((z - 1j)*(z + 1j)) / ((z - exp(1j*pi/4))*(z - exp(-1j*pi/4)))


4. H= ((z - 0.5 - 0.5j)*(z - 0.5 + 0.5j)) / ((z - 0.7 - 0.2j)*(z - 0.7 + 0.2j))

5. H = 1 / ((z - 0.9*exp(1j*pi/10))*(z - 0.9*exp(-1j*pi/10)))


Conclusion:
Through this experiment,we come to know about the formula of z-
transform and the inbuilt function both and found the zeroes of the z-
transformed function.
LAB-3
AIM : To implement inverse Z-transform with and without
using inbuilt function in MATLAB.
CODE :
clc;
clear all;
close all;

syms z n;
a=0.2;
w = 1 / (1 - a*z^(-1));
disp(iztrans(w, z, n));

b = 0.5;
x = 1 / (1 - b*z^(-1));
disp(iztrans(x, z, n));

y=z^(-1) / (1 - 0.5*z^(-1));
disp(iztrans(y, z, n));

wx= 1 / ((1 - 0.4*z^(-1))*(1 - 0.6*z^(-1)));


disp(iztrans(wx, z, n));

xy=z/(z-1);
disp(iztrans(xy, z, n));

OUTPUT:

CONCLUSION:

Through this experiment, we determined the inverse z-transform of


some functions, and we came to know about the inbuilt functions as
well.
LAB-4
AIM : To implement DFT and IDFT using Direct method in
MATLAB.
CODE :
clc;
clear;
close all;

% Function-1
N = 4; % Number of samples
x = [1,2,2,1];

X=DFT(4,[1,2,2,1]);
% Display original sequence and DFT result
disp('Input Original Sequence:');
disp(x);
disp('DFT Result:');
disp(X);

x_reconstructed=IDFT(N,X);
% Display reconstructed sequence using IDFT
disp('Reconstructed Sequence using IDFT:');
disp(x_reconstructed);

% Function-2
N = 5; % Number of samples
n = 0:N-1; % Time indices
f = 0.3;
x = exp(1j*2*pi*f*n);

X=DFT(N,x);
% Display original sequence and DFT result
disp('Input Original Sequence:');
disp(x);
disp('DFT Result:');
disp(X);

x_reconstructed=IDFT(N,X);
% Display reconstructed sequence using IDFT
disp('Reconstructed Sequence using IDFT:');
disp(x_reconstructed);

% Function-3
N = 5; % Number of samples
x = [9,4,1,2,9];

X=DFT(N,x);
% Display original sequence and DFT result
disp('Input Original Sequence:');
disp(x);
disp('DFT Result:');
disp(X);

x_reconstructed=IDFT(N,X);
% Display reconstructed sequence using IDFT
disp('Reconstructed Sequence using IDFT:');
disp(x_reconstructed);

% Function-4
N = 16; % Number of samples
n = 0:N-1; % Time indices
f = 0.25; % Frequency of the signal
x = cos(2*pi*f*n); % Input signal

X=DFT(N,x);
% Display original sequence and DFT result
disp('Input Original Sequence:');
disp(x);
disp('DFT Result:');
disp(X);

x_reconstructed=IDFT(N,X);
% Display reconstructed sequence using IDFT
disp('Reconstructed Sequence using IDFT:');
disp(x_reconstructed);

% Function-5
N = 6; % Number of samples
x = [19,12,3,4,9,2];

X=DFT(N,x);
% Display original sequence and DFT result
disp('Input Original Sequence:');
disp(x);
disp('DFT Result:');
disp(X);

x_reconstructed=IDFT(N,X);
% Display reconstructed sequence using IDFT
disp('Reconstructed Sequence using IDFT:');
disp(x_reconstructed);

function res=DFT(s,x)
X = zeros(1, s); % Initialize DFT result

for k = 1:s
for n = 1:s
X(k) = X(k) + x(n) * exp(-1j*2*pi*(k-1)*(n-1)/s);
end
end
res=X;
end

function res2=IDFT(s,X)
x_reconstructed = zeros(1, s); % Initialize reconstructed signal
for n = 1:s
for k = 1:s
x_reconstructed(n) = x_reconstructed(n) + (1/s) * X(k) *
exp(1j*2*pi*(k-1)*(n-1)/s);
end
end
res2=x_reconstructed;
end

OUTPUT:

CONCLUSION:

In conclusion, we implemented DFT and IDFT using the direct method in


MATLAB. Through various signal examples, we explored frequency
analysis and signal reconstruction, enhancing our understanding of
these fundamental operations.
LAB-5
AIM : To perform circular convolution
1.by using inbuilt dft and idft function
2.by using user defined dft and idft functions
3.by using matrix multiplication technique
4.by using concentric circle method
CODE :

Task-1
clc;
clear;
close all;

%
% %DIsplay circle
% n=0:0.01:1;
% a=sin(2*pi*n);
% b=cos(2*pi*n);
% plot(a,b);
%
% m = input('Enter number of points');
% thetao = 2*pi/m;
% theta = thetao;
% for i=1:m
% text(sin(theta),cos(theta),'o');
% theta = theta + thetao;
% end

% Circular Convolution using DFT and IDFT

x = input('Enter the first sequence x[n]: ');


h = input('Enter the second sequence h[n]: ');

N = length(x);
M = length(h);

% Zero-pad the sequences to make their lengths equal


if N < M
x = [x zeros(1, M-N)];
elseif N > M
h = [h zeros(1, N-M)];
end

% Compute DFT of the sequences


X = fft(x);
H = fft(h);
disp('DFT of x:');
disp(X);
disp('DFT of h:');
disp(H);

% Perform element-wise multiplication in the frequency domain


Y = X .* H;

% Compute IDFT of the result


y = ifft(Y);
disp('IDFT:');
disp(y);

% Display the circular convolution result


disp('Circular Convolution using DFT and IDFT:');
disp(y);

Task-2
clc;
clear;
close all;

% Circular Convolution using DFT and IDFT

x = input('Enter the first sequence x[n]: ');


h = input('Enter the second sequence h[n]: ');

N = length(x);
M = length(h);

% Zero-pad the sequences to make their lengths equal


if N < M
x = [x zeros(1, M-N)];
elseif N > M
h = [h zeros(1, N-M)];
end

% Compute DFT of the sequences using custom DFT function


X = myDFT(x);
H = myDFT(h);
disp('DFT of x:');
disp(X);
disp('DFT of h:');
disp(H);

% Perform element-wise multiplication in the frequency domain


Y = X .* H;

% Compute IDFT of the result using custom IDFT function


y = myIDFT(Y);
disp('Circular Convolution using DFT and IDFT:');
disp(y);

% Custom DFT function


function X = myDFT(x)
N = length(x);
n = 0:N-1;
k = 0:N-1;
WN = exp(-1j*2*pi/N);
nk = n.' * k;
W = WN .^ nk;
X = x * W;
end

% Custom IDFT function


function x = myIDFT(X)
N = length(X);
n = 0:N-1;
k = 0:N-1;
WN = exp(1j*2*pi/N);
nk = n.' * k;
W = WN .^ nk;
x = (1/N) * X * W;
end

Task-3
clc;
clear;
close all;

% Circular Convolution using Matrix Multiplication

x = input('Enter the first sequence x[n]: ');


h = input('Enter the second sequence h[n]: ');

N = length(x);
M = length(h);

% Zero-pad the sequences to make their lengths equal


if N < M
x = [x zeros(1, M-N)];
elseif N > M
h = [h zeros(1, N-M)];
end

% Create the circular convolution matrix


C = zeros(N, N);
for n = 1:N
C(n, :) = circshift(h, [0, n]);
end

% Compute the circular convolution using matrix multiplication


y = x * C.';

% Display the circular convolution result


disp('Circular Convolution using Matrix Multiplication:');
disp(y);

Task-4
clc;
clear all;
close all;
% Example usage with different input functions and varying lengths

x_sequence_1 = input('Enter the first sequence x[n]: '); % Sample sequence

x_sequence_2 = input('Enter the second sequence h[n]: '); % Sample sequence

N = max(length(x_sequence_1), length(x_sequence_2));
%DIsplay circle
n=0:0.01:1;
a=sin(2*pi*n);
b=cos(2*pi*n);
m = N;
thetao = 2*pi/m;
x1 = x_sequence_1;

x3 = flip(x_sequence_2);
for i = 1:N
subplot(N,3,(3*i - 2));
plot(a,b);
theta = 0;
for j=1:m
val = int2str(x1(j));
text(cos(theta),sin(theta), val);
theta = theta + thetao;
end
x3 = circshift(x3, 1);
subplot(N,3,(3*i - 1));
plot(a,b);
theta = 0;
for j=1:m
val = int2str(x3(j));
text(cos(theta),sin(theta), val);
theta = theta + thetao;
end
x4 = x1.*x3;
subplot(N,3,3*i);
plot(a,b);
theta = 0;
for j=1:m
val = int2str(x4(j));
text(cos(theta),sin(theta), val);
theta = theta + thetao;
end
x5(i) = sum(x1.*x3);
end

disp('Circular Convolution using DFT and IDFT for Input :');


disp(x5);
OUTPUT:

Task-1

Task-2
Task-3
Task-2

Task-4

CONCLUSION:

The implementation of circular convolution for two time-domain signals


has been explored through various methods: direct function, inbuilt
function, twiddle factor, and concentric circle method. Each approach
offers its own set of advantages and considerations.
LAB-6
AIM : To implement DIT-FFT algorithm for calculating Fast
fourier transform.
CODE :
clc;
clear all;
close all;
% Define your input sequence
x = input('Enter sequence 1: ');

% Call the FFT function


X = fft_dit(x);

% Display the FFT result


disp(X);

function X = fft_dit(x)
N = length(x);

if N <= 1
X = x;
else
% Split the input into even and odd-indexed elements
x_even = x(1:2:N);
x_odd = x(2:2:N);

% Recursive FFT on even and odd parts


X_even = fft_dit(x_even);
X_odd = fft_dit(x_odd);

% Combine the results


twiddle_factors = exp(-2i * pi * (0:(N/2 - 1)) / N);
X = [X_even + twiddle_factors .* X_odd, X_even - twiddle_factors .*
X_odd];
end
end

OUTPUT:

DIT-FFT Code
2-point DIT-FFT

4-point DIT-FFT

CONCLUSION:

The implementation of the Decimation in Time Fast Fourier Transform


(DIT-FFT) algorithm provides an efficient and widely used method for
calculating the Fast Fourier Transform (FFT). The DIT-FFT algorithm is a
radix-2 algorithm, which recursively breaks down a Fourier transform
into smaller transforms..
LAB-7
AIM : To implement DIF-FFT algorithm for calculating Fast
fourier transform.
CODE :
clc;
clc;
clear all;
close all;
while true
% Prompt the user for input sequence
user_input = input('Enter the sequence (space-separated values) or type "exit"
to quit: ', 's');

% Check if the user wants to exit


if strcmpi(user_input, 'exit')
disp('Exiting the program.');
break;
end

% Parse the input sequence


x = str2num(user_input);

% Check if the input is numeric


if isempty(x)
disp('Invalid input. Please enter numeric values.');
continue;
end

% Check if the length of the input sequence is a power of 2


N = length(x);
if log2(N) ~= round(log2(N))
disp('Input sequence length should be a power of 2.');
continue;
end

% Compute the DIF FFT of the input sequence


X = dif_fft(x);
X = bitrevorder(X);

% Display the FFT result


disp('FFT Result:');
disp(X);
end

function X = dif_fft(x)
N = length(x);

% Base case: DFT of length 2


if N == 2
X = [x(1) + x(2), x(1) - x(2)];
return;
end

% Calculate twiddle factors in natural order


twiddle = exp(-2i*pi*(0:N/2-1)/N);

% Split the input into straight halves


x_left = x(1:N/2);
x_right = x(N/2+1:N);

% Combine the results using twiddle factors


X = zeros(1, N);
for k = 1:N/2
X(k) = x_left(k) + x_right(k);
X(k + N/2) = (x_left(k) - x_right(k))*twiddle(k);
end

% Recursive FFT computation after computation


X(1:N/2) = dif_fft(X(1:N/2));
X(N/2+1:N) = dif_fft(X(N/2+1:N));
end

OUTPUT:

DIF-FFT Code

4-point DIT-FFT
8-point DIT-FFT

CONCLUSION:

DIF-FFT, or Decimation in Frequency Fast Fourier Transform, is a highly


efficient algorithm for computing the Fast Fourier Transform (FFT). By
recursively dividing the input sequence, it achieves a time complexity of
O(N log N). Widely used in signal and image processing, DIF-FFT is
fundamental for rapid FFT calculations.
LAB-8
AIM : To study and plot the frequency response of digital
system or filter. Also calculate the cut-off frequencies and
transfer functions of low pass,high pass, band pass, and band
stop filters.
CODE :
Low Pass Filter
clc;
clear all;
close all;
%FIR low-pass filter
% Define filter parameters
filter_order = 100; % Filter order
cutoff_frequency = 100; % Cutoff frequency (Hz)
Fs = 1000; % Sampling frequency (Hz)

% Calculate normalized cutoff frequency


normalized_cutoff = cutoff_frequency / (0.5 * Fs);

% Calculate the transfer function of the low-pass filter


numerator = fir1(filter_order, normalized_cutoff, 'low');
denominator = 1;

% Compute the frequency response


frequencies = linspace(0, Fs / 2, 1000); % Frequency range up to Nyquist
frequency
[H,F] = freqz(numerator, denominator, frequencies, Fs);

c = max(abs(H)) / sqrt(2);
indices = find(abs(H) >= c);
cutoff_freq=F(indices);

% Calculate magnitude and phase


magnitude = abs(H);
phase = angle(H);

% Print the calculated cutoff frequency


disp(['Cutoff Frequency: ' num2str(cutoff_freq(end)) ' Hz']);

% Plot the magnitude response


figure;
subplot(2, 1, 1);
plot(frequencies, 20 * log10(magnitude)); % Convert to dB scale
xlabel('Frequency (Hz)');
ylabel('Magnitude (dB)');
axis([0 500 -140 20]);
title('Magnitude Response of Low-Pass Filter');
% Plot the phase response
subplot(2, 1, 2);
plot(frequencies, phase);
xlabel('Frequency (Hz)');
ylabel('Phase (radians)');
title('Phase Response of Low-Pass Filter');

High Pass Filter


clc;
clear all;
close all;
%FIR high-pass filter
% Define filter parameters
filter_order = 50; % Filter order
cutoff_frequency = 100; % Cutoff frequency (Hz)
Fs = 1000; % Sampling frequency (Hz)

% Calculate normalized cutoff frequency


normalized_cutoff = cutoff_frequency / (0.5 * Fs);

% Calculate the transfer function of the high-pass filter


numerator = fir1(filter_order, normalized_cutoff, 'high');
denominator = 1;

% Compute the frequency response


frequencies = linspace(0, Fs / 2, 1000); % Frequency range up to Nyquist
frequency
[H,F] = freqz(numerator, denominator, frequencies, Fs);

c = max(abs(H)) / sqrt(2);
indices = find(abs(H) >= c);
cutoff_freq=F(indices);

% Calculate magnitude and phase


magnitude = abs(H);
phase = angle(H);

% Print the calculated cutoff frequency


disp(['Cutoff Frequency: ' num2str(cutoff_freq(1)) ' Hz']);

% Plot the magnitude response


figure;
subplot(2, 1, 1);
plot(frequencies, 20 * log10(magnitude)); % Convert to dB scale
xlabel('Frequency (Hz)');
ylabel('Magnitude (dB)');
title('Magnitude Response of High-Pass Filter');

% Plot the phase response


subplot(2, 1, 2);
plot(frequencies, phase);
xlabel('Frequency (Hz)');
ylabel('Phase (radians)');
title('Phase Response of High-Pass Filter');
Band Pass Filter
clc;
clear all;
close all;
% FIR bandpass filter

% Define filter parameters


filter_order = 50; % Filter order
lower_cutoff_frequency = 100; % Lower cutoff frequency (Hz)
upper_cutoff_frequency = 300; % Upper cutoff frequency (Hz)
Fs = 1000; % Sampling frequency (Hz)

% Calculate normalized cutoff frequencies


normalized_lower_cutoff = lower_cutoff_frequency / (0.5 * Fs);
normalized_upper_cutoff = upper_cutoff_frequency / (0.5 * Fs);

% Calculate the transfer function of the band-pass filter


numerator = fir1(filter_order, [normalized_lower_cutoff, normalized_upper_cutoff], 'band');
denominator = 1;

% Compute the frequency response


frequencies = linspace(0, Fs / 2, 1000); % Frequency range up to Nyquist frequency
[H,F] = freqz(numerator, denominator, frequencies, Fs);

c = max(abs(H)) / sqrt(2);
indices = find(abs(H) >= c);
cutoff_freq=F(indices);

% Calculate magnitude and phase


magnitude = abs(H);
phase = angle(H);

% Print the calculated cutoff frequencies


disp(['Lower Cutoff Frequency: ' num2str(cutoff_freq(1)) ' Hz']);
disp(['Upper Cutoff Frequency: ' num2str(cutoff_freq(end)) ' Hz']);
% Plot the magnitude response
figure;
subplot(2, 1, 1);
plot(frequencies, 20 * log10(magnitude)); % Convert to dB scale
xlabel('Frequency (Hz)');
ylabel('Magnitude (dB)');
axis([0 500 -140 20]);
title('Magnitude Response of Band-Pass Filter');

% Plot the phase response


subplot(2, 1, 2);
plot(frequencies, phase);
xlabel('Frequency (Hz)');
ylabel('Phase (radians)');
title('Phase Response of Band-Pass Filter');

Band Stop Filter


clc;
clear all;
close all;
%FIR bandstop filter
% Define filter parameters
filter_order = 100; % Filter order
lower_cutoff_frequency = 40; % Lower cutoff frequency (Hz)
upper_cutoff_frequency = 60; % Upper cutoff frequency (Hz)
Fs = 1000; % Sampling frequency (Hz)

% Calculate normalized cutoff frequencies


normalized_lower_cutoff = lower_cutoff_frequency / (0.5 * Fs);
normalized_upper_cutoff = upper_cutoff_frequency / (0.5 * Fs);

% Calculate the transfer function of the band-stop filter


numerator = fir1(filter_order, [normalized_lower_cutoff, normalized_upper_cutoff], 'stop');
denominator = 1;

% Compute the frequency response


frequencies = linspace(0, Fs / 2, 1000); % Frequency range up to Nyquist frequency
[H,F] = freqz(numerator, denominator, frequencies, Fs);

c = max(abs(H)) / sqrt(2);
indices = find(abs(H) <= c);
cutoff_freq=F(indices);

% Calculate magnitude and phase


magnitude = abs(H);
phase = angle(H);

% Print the calculated cutoff frequencies


disp(['Lower Cutoff Frequency: ' num2str(cutoff_freq(1)) ' Hz']);
disp(['Upper Cutoff Frequency: ' num2str(cutoff_freq(end)) ' Hz']);

% Plot the magnitude response


figure;
subplot(2, 1, 1);
plot(frequencies, 20 * log10(magnitude)); % Convert to dB scale
xlabel('Frequency (Hz)');
ylabel('Magnitude (dB)');
title('Magnitude Response of Band-Stop Filter');

% Plot the phase response


subplot(2, 1, 2);
plot(frequencies, phase);
xlabel('Frequency (Hz)');
ylabel('Phase (radians)');
title('Phase Response of Band-Stop Filter');
OUTPUT:
Low Pass Filter

High Pass Filter


Band Pass Filter

Band Stop Filter


CONCLUSION:

The frequency response of digital systems or filters was


comprehensively examined and plotted. The analysis involved
calculating essential parameters such as cut-off frequencies and
transfer functions for various filter types, including low-pass, high-
pass, band-pass, and band-stop filters. The frequency response graphs
provided insights into how these filters affect different frequency
components, contributing to a better understanding of their behavior
and applications in signal processing. The study enhances knowledge of
digital systems and equips practitioners with tools for designing filters
tailored to specific frequency ranges and requirements.
LAB-9
AIM : To realize the digital system & filter using Direct
Form,Cascade Form and Parallel Form in matlab as well as
simulink.
CODE :
clc;
% Define filter coefficients (replace these with your own values)
b = [1 0.5]; % Numerator coefficients
a = [1 -0.8]; % Denominator coefficients

% Define a predefined function as your input signal


t = linspace(0, 1, 1000); % Time vector from 0 to 1
x = sin(2*pi*5*t) + 0.5*cos(2*pi*10*t); % Example predefined function

% Initialize filter state variables


N = max(length(b), length(a));
x_n = zeros(1, N);
y_n = zeros(1, N);

% Store frequency responses


H = zeros(1024, 3); % Direct, Parallel, Cascade

forms = ["Direct", "Parallel", "Cascade"];

% Calculate outputs and frequency responses for each form


for i = 1:length(forms)
form = forms(i);

% Apply Direct Form I


if form == "Direct"
y = zeros(size(x));
for n = 1:length(x)
% Shift input and output state variables
x_n = [x(n), x_n(1:N-1)];
y_n = [y(n), y_n(1:N-1)];

% Calculate output
y(n) = b * x_n' - a(2:end) * y_n(2:end)';
end
end

% Apply Parallel Form using Partial Fraction Decomposition


if form == "Parallel"
[R, P, K] = residue(b, a);

% Display Partial Fraction Decomposition in Output Window


fprintf('Partial Fraction Decomposition for Parallel Form:\n');
for j = 1:length(R)
fprintf('Term %d: %f / (z - %f)\n', j, R(j), P(j));
end

y = zeros(size(x));
for j = 1:length(R)
% Calculate contribution of each term
y_j = R(j) * P(j)^(-1) * (1 - exp(P(j) * x));
y = y + y_j;
end
end

% Apply Cascade Form


if form == "Cascade"
y = zeros(size(x));
for n = 1:length(x)
% Shift input and output state variables
x_n = [x(n), x_n(1:N-1)];
y_n = [y(n), y_n(1:N-1)];

% Calculate output
y(n) = b(1) * (sum(b .* x_n) - sum(a(2:end) .* y_n(2:end)));
end
end

% Calculate Frequency Response


Nfft = 1024; % Number of points for FFT
[H(:,i), f] = freqz(b, a, Nfft, 'half', 1);

% Display Transfer Function


fprintf('Transfer Function (%s):\n', form);
fprintf('H(z) = ');
for j = 1:length(b)
fprintf('%fz^(-%d) ', b(j), j-1);
if j < length(b)
fprintf('+ ');
end
end
fprintf('/ ');
for j = 1:length(a)
fprintf('%fz^(-%d) ', a(j), j-1);
if j < length(a)
fprintf('+ ');
end
end
fprintf('\n\n');
end

% Plot Input Function (Only Once)


figure;
subplot(3, 2, [1, 2]);
plot(t, x);
title('Input Function');
xlabel('Time');
ylabel('Amplitude');

% Plot Amplitude Response, Poles, and Zeros for Direct Form


subplot(3, 2, 3);
plot(f, abs(H(:,1)));
title('Amplitude Response (Direct Form)');
xlabel('Frequency (Hz)');
ylabel('Magnitude');
subplot(3, 2, 4);
zplane(b, a);
title('Poles and Zeros (Direct Form)');

% Create a new figure for Parallel Form


figure;
subplot(3, 2, 1);
plot(t, x);
title('Input Function');
xlabel('Time');
ylabel('Amplitude');

% Plot Amplitude Response for Parallel Form


subplot(3, 2, 2);
plot(f, abs(H(:,2)));
title('Amplitude Response (Parallel Form)');
xlabel('Frequency (Hz)');
ylabel('Magnitude');

% Create a new figure for Cascade Form


figure;
subplot(3, 2, 1);
plot(t, x);
title('Input Function');
xlabel('Time');
ylabel('Amplitude');

% Plot Amplitude Response for Cascade Form


subplot(3, 2, 2);
plot(f, abs(H(:,3)));
title('Amplitude Response (Cascade Form)');
xlabel('Frequency (Hz)');
ylabel('Magnitude');

OUTPUT:
CONCLUSION:

This lab focused on implementing a digital system and filter using


various structures—Direct Form, Cascade Form, and Parallel Form. The
realization occurred in MATLAB and Simulink, offering a practical
analysis of each architecture's strengths and weaknesses. By
comparing their performance, this study provided insights into selecting
the most suitable form based on specific design criteria and
computational efficiency.
LAB-10
AIM : To implement linear phase characteristics of FIR
discrete digital filters using MATLAB
CODE :
% Linear Phase Characteristics in DSP for Four Cases
clc;
clear all;
close all;
h_odd_even = [1, 3, 5, 7, 5, 3, 1]; % Example sequence for Odd Length Even
Symmetry
h_even_even = [1, 3, 5, 7, 7, 5, 3, 1]; % Example sequence for Even Length Even
Symmetry
h_odd_odd = [1, 3, 5, 0, -5, -3, -1]; % Example sequence for Odd Length Odd
Symmetry
h_even_odd = [1, 3, 5, 7, -7, -5, -3, -1]; % Example sequence for Even Length
Odd Symmetry
plotLinearPhaseFilterResponse(h_odd_even);
plotLinearPhaseFilterResponse(h_even_even);
plotLinearPhaseFilterResponse(h_odd_odd);
plotLinearPhaseFilterResponse(h_even_odd);
function plotLinearPhaseFilterResponse(desired_impulse_response)
% Design the filter coefficients manually to match the desired impulse
response
N = length(desired_impulse_response) - 1;
b = [desired_impulse_response(N+1:-1:1)];
% Calculate the impulse response
impulse_response = impz(b, 1);
n = 0:N; % Create a time index from 0 to N
% Calculate the frequency response
[H, w] = freqz(b, 1);
[phs, w1] = phasez(b, 1);
% Convert magnitude to dB and phase to degrees
magnitude_dB = 20 * log10(abs(H));
phase_degrees = rad2deg(phs);
% Create a single figure for all plots
figure;
% Plot the impulse response
subplot(3, 1, 1);
stem(n, impulse_response);
title('Impulse Response');
xlabel('Sample Number');
ylabel('Amplitude');
% Create a normalized frequency axis
normalized_freq = w / pi;
% Plot the magnitude response in dB
subplot(3, 1, 2);
plot(normalized_freq, magnitude_dB);
title('Magnitude Response (dB)');
xlabel('Normalized Frequency');
ylabel('Magnitude (dB)');
% Plot the phase response in degrees
subplot(3, 1, 3);
plot(normalized_freq, phase_degrees);
title('Phase Response (degrees)');
xlabel('Normalized Frequency');
ylabel('Phase (degrees)');
% Make the plots look nice
% sgtitle('Linear Phase Filter Impulse and Frequency Response');
End

OUTPUT:
Odd Length ,Even Symmetry

Even Length ,Even Symmetry


Odd Length ,Odd Symmetry

Even Length ,Odd Symmetry

CONCLUSION:
This lab aimed to implement linear phase characteristics of Finite
Impulse Response (FIR) discrete digital filters using MATLAB. Through
rigorous design and analysis, the objective was to achieve linear phase
response, a crucial property in various signal processing applications.
The study involved coding and simulation in MATLAB, showcasing the
effectiveness of the implemented FIR filters in preserving the phase
relationship of input signals across different frequencies
LAB-11
AIM : To implement various window methods to obtain FIR
filter response from IIR signal using MATLAB.

CODE :
Rectangular Window
% Define parameters
N = 45; % Window length
cutoff = 0.2; % Cutoff frequency
Fs = 1000; % Sampling frequency

% Generate the Rectangular window


rectangular_window = rectwin(N);

% Plot the Rectangular Window in Time Domain


figure;
subplot(2, 1, 1);
stem(rectangular_window);
title('Rectangular Window in Time Domain');
xlabel('Sample');
ylabel('Amplitude');

b = fir1(N-1, cutoff,"low",rectangular_window);

% Frequency Response Plot


[H, w] = freqz(b, 1, 1024, Fs);

subplot(2, 1, 2);
plot(w, 20*log10(abs(H)));
title('Low-Pass Filter Frequency Response');
xlabel('Frequency (Hz)');
ylabel('Magnitude (dB)');

% Display plots
% sgtitle('Low-Pass FIR Filter Plots with Rectangular Window');

Triangular Window

% Define parameters
N = 45; % Window length
cutoff = 0.2; % Cutoff frequency
Fs = 1000; % Sampling frequency

% Generate the Rectangular window


triangular_window = triang(N);

% Plot the Rectangular Window in Time Domain


figure;
subplot(2, 1, 1);
stem(triangular_window);
title('Triangular Window in Time Domain');
xlabel('Sample');
ylabel('Amplitude');

% Design the low-pass filter (modify for your application)


b = fir1(N-1, cutoff,"low",triangular_window);

% Frequency Response Plot


[H, w] = freqz(b, 1, 1024, Fs);

subplot(2, 1, 2);
plot(w, 20*log10(abs(H)));
title('Low-Pass Filter Frequency Response');
xlabel('Frequency (Hz)');
ylabel('Magnitude (dB)');

% Display plots
% sgtitle('Low-Pass FIR Filter Plots with Triangular Window');

Blackman Window

% Define parameters
N = 45; % Filter order
cutoff = 0.2; % Cutoff frequency
Fs = 1000; % Sampling frequency

figure;
% Generate the Hamming window
blackman_window = blackman(N);

% Time Domain Window Plot


subplot(2, 1, 1);
stem(blackman_window);
title('Blackman window in Time Domain');
xlabel('Sample');
ylabel('Amplitude');

% Design the low-pass filter


b = fir1(N-1, cutoff,"low",blackman_window);

% Frequency Response Plot


[H, w] = freqz(b, 1, 1024, Fs);

subplot(2, 1, 2);
plot(w, 20*log10(abs(H)));
title('Low-Pass Filter Frequency Response');
xlabel('Frequency (Hz)');
ylabel('Magnitude (dB)');

% Display plots
% sgtitle('Low-Pass FIR Filter Plots with Blackman Window');
Hamming Window

% Define parameters
N = 45; % Filter order
cutoff = 0.2; % Cutoff frequency
Fs = 1000; % Sampling frequency

figure;
% Generate the Hamming window
hamming_window = hamming(N);

% Time Domain Window Plot


subplot(2, 1, 1);
stem(hamming_window);
title('Hamming Window in Time Domain');
xlabel('Sample');
ylabel('Amplitude');

% Design the low-pass filter


b = fir1(N-1, cutoff,"low",hamming_window);

% Frequency Response Plot


[H, w] = freqz(b, 1, 1024, Fs);

subplot(2, 1, 2);
plot(w, 20*log10(abs(H)));
title('Low-Pass Filter Frequency Response');
xlabel('Frequency (Hz)');
ylabel('Magnitude (dB)');

% Display plots
% sgtitle('Low-Pass FIR Filter Plots with Hamming Window');

Hanning Window

% Define parameters
N = 45; % Filter order
cutoff = 0.2; % Cutoff frequency
Fs = 1000; % Sampling frequency

figure;
% Generate the Hamming window
hanning_window = hann(N);

% Time Domain Window Plot


subplot(2, 1, 1);
stem(hanning_window);
title('Hanning Window in Time Domain');
xlabel('Sample');
ylabel('Amplitude');

% Design the low-pass filter


b = fir1(N-1, cutoff,"low",hanning_window);

% Frequency Response Plot


[H, w] = freqz(b, 1, 1024, Fs);

subplot(2, 1, 2);
plot(w, 20*log10(abs(H)));
title('Low-Pass Filter Frequency Response');
xlabel('Frequency (Hz)');
ylabel('Magnitude (dB)');

% Display plots
% sgtitle('Low-Pass FIR Filter Plots with Hanning Window');

Kaiser Window

% Define parameters
N = 45; % Filter order
cutoff = 0.2; % Cutoff frequency
Fs = 1000; % Sampling frequency

figure;
% Generate the Rectangular window
beta=3;
kaiser_win = kaiser(N,beta);

% Time Domain Window Plot


subplot(2, 1, 1);
stem(kaiser_win);
title('Kaiser Window in Time Domain');
xlabel('Sample');
ylabel('Amplitude');

% Design the low-pass filter


b = fir1(N-1, cutoff,"low",kaiser_win);

% Frequency Response Plot


[H, w] = freqz(b, 1, 1024, Fs);

subplot(2, 1, 2);
plot(w, 20*log10(abs(H)));
title('Low-Pass Filter Frequency Response');
xlabel('Frequency (Hz)');
ylabel('Magnitude (dB)');

% Display plots
% sgtitle('Low-Pass FIR Filter Plots with Kaiser Window');

OUTPUT:
Rectangular Window
Triangular Window

Blackman Window
Hamming Window

Hanning Window
Kaiser Window

CONCLUSION:
In this lab, various window methods were implemented to obtain Finite
Impulse Response (FIR) filter responses from Infinite Impulse
Response (IIR) signals using MATLAB. By applying different window
functions, such as Hamming, Blackman, and Kaiser, the goal was to
analyze their impact on the filter's frequency response. This study
provided insights into selecting appropriate windowing techniques for
transforming IIR signals into FIR filters with desired characteristics,
enhancing the understanding of signal processing methodologies.
LAB-12
AIM : To implement IIR filter realisation using Bilinear
transformation and Impulse Invariance method.

CODE :
% IIR Filter Design using Impulse Invariant and Bilinear Transform Methods

% Filter specifications
fs = 1000; % Sampling frequency
fc = 100; % Cutoff frequency
order = 4; % Filter order

% Design analog Butterworth filter


[b, a] = butter(order, 2 * fc / fs, 's');

% Impulse Invariant transformation


[num_imp, den_imp] = impinvar(b, a, fs);

% Bilinear transformation
[num_bilin, den_bilin] = bilinear(b, a, fs);

% Frequency response plots


f = linspace(0, fs/2, 1024);

% Frequency response of the impulse invariant filter


[h_imp, w_imp] = freqz(num_imp, den_imp, f, fs);

% Frequency response of the bilinear transform filter


[h_bilin, w_bilin] = freqz(num_bilin, den_bilin, f, fs);

% Plot the magnitude responses


figure;
subplot(2,2,1);
plot(w_imp, 20*log10(abs(h_imp)));
title('Impulse Invariant Method - Magnitude Response');
xlabel('Frequency (Hz)');
ylabel('Magnitude (dB)');
grid on;

subplot(2,2,3);
plot(w_bilin, 20*log10(abs(h_bilin)));
title('Bilinear Transform Method - Magnitude Response');
xlabel('Frequency (Hz)');
ylabel('Magnitude (dB)');
grid on;

% Plot the phase responses


subplot(2,2,2);
plot(w_imp, angle(h_imp));
title('Impulse Invariant Method - Phase Response');
xlabel('Frequency (Hz)');
ylabel('Phase (radians)');
grid on;

subplot(2,2,4);
plot(w_bilin, angle(h_bilin));
title('Bilinear Transform Method - Phase Response');
xlabel('Frequency (Hz)');
ylabel('Phase (radians)');
grid on;

OUTPUT:

CONCLUSION:

In this lab,we implemented the realization of Infinite Impulse Response


(IIR) filters using two different methods: Bilinear Transformation and
Impulse Invariance. The Bilinear Transformation method involves
mapping continuous-time IIR filters to discrete-time equivalents,
preserving stability and frequency response. On the other hand, the
Impulse Invariance method directly transforms continuous-time filter
impulse responses to discrete-time versions. By comparing and
analyzing these methods, the project aimed to provide insights into the
trade-offs and considerations involved in implementing IIR filters in
practical applications.

You might also like