0% found this document useful (0 votes)
39 views

Matlab

Python matlab

Uploaded by

salmanul farisi
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
39 views

Matlab

Python matlab

Uploaded by

salmanul farisi
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 70

GOVERNMENT ENGINEERING COLLEGE

KOZHIKODE, KERALA-673005

ECL 333 DIGITAL SIGNAL PROCESSING LAB

SALMANUL FARISI
Name: ………………………………………………………………………………………..
8421
Admission no.: ……………………… 2021
Year of admission:………………………
62
Roll no.:…………………………………… Semester& Branch: S5, ECE

Certified that this is a bonafide record of work done by

SALMANUL FARISI
……………………………………………………………………………………………………

Kozhikode Staff in charge


Date:…………..

Submitted for practical examination held on ………………………….

Reg. no.: KKE21EC050

Internal Examiner External Examiner


INDEX
Sl. Date Name of experiment Page
No. no.
Matlab based experiments
1 Simulation of signals 1
2 Verification and properties of 10
DFT
3 Circular convolution 38
4 Parseval’s Theorem 42
5 Overlap and add block
45
convolution
6 Overlap and save block
50
convolution
7 FIR filter design 55
DSP Processor based experiments
1 Inner Product Computation 65
2 Convolution (FIR Filtering) 66
Experiment No:1

SIMULATION OF SIGNALS
Date:04/10/2023

Aim:
Simulate following signals :

1.Unit Impulse Signal

2.Unit Pulse Signal

3.Unit Ramp Signal

4.Bipolar Pulse

5.Triangular Signal

6.Sinusoidal Signal

7.Composite Sinusoidal Signal

Theory:
In signal processing experiments, we need the help of some fundamental signals such as sine wave, square
wave, ramp wave, unit step, unit impulse etc. A digital signal can be either a deterministic signal that can
be predicted with certainity, or a random signal that is unpredictable. Due to ease in signal generation and
need for predictability, deterministic signal can be used for system simulation studies. Standard forms of some
deterministic signals that are frequently used in DSP are discussed below:

1. Impulse: The simplest signal is the unit impulse signal represent an instantaneous,infinitely high signal at t=0

δ (n) = 1 for n = 0

= 0 for n ≠ 0

2. Unit Pulse Signal: The unit pulse signal,also lknown as the unit step function, becomes 1 for t>0 and
remains at t<0. it signifies the a sudden change opr initiation in a system.

u(t)={0, for t<0;1, for t ≥0}

3. Ramp: The Ramp signal is a linearily increasing function for t>0 and zero elsewhere.it represents a
gradual,linear growth or change in a system.

r(t)=t*u(t)

r (n) = n for n ≥ 0

= 0 for n < 0

4.Bipolar pulse signal:The bipolar pulse signal includes both positive and negative pulses.it can be formed by
subtracting two unit step functions occuring at different times

1
bipolar_pulse(t)= u(t-t1)-u(t-t2)

5.Triangular signal: The triangular signal is formed by convolving two unit pulse signals.It represents a
symmetric triangular waveform.

triangular_signal(t)=conv(u(t),u(t))

6. Sinusoidal Signal: A sinusoidal sequence is defined as,

x(n) = 2*pi*(F/Fs)*n

7.Composite Sinusoidal Signal: A composite sinusoidal signal combines multiple sinusoidal signals with
different frequencies, amplitudes, and phases.

sin(2*pi*(f1/fs)*n+0.5*sin(2*pi*(f2/fs)*n)+0.75*sin(2*pi*(f3/fs)*n))

Programs and Observations

1. Generation of unit impulse signal

clc
clear all
% Define the range of values for the variable n
n_START=-200;
n_END=200;
% Calculate the midpoint of the range (including zero
n_ZERO=(abs(n_START)+abs(n_END))/2+1;
% Initialize an array for the unit impulse signal
unit_impulse=zeros(abs(n_START)+abs(n_END)+1,1);
% Set the value corresponding to the unit impulse at the midpoint
unit_impulse(n_ZERO)=1;
% Define the range of values for n
n=n_START:n_END;
% Plot the unit impulse using stem with specified attributes
stem(n,unit_impulse,marker='none',LineWidth=2,Color='r'),grid on
% Label the x-axis, y-axis, and provide a title for the plot
xlabel('n')
ylabel('x(n)')
title('UNIT IMPULSE')

2
2. Generation of unit pulse

% Define the range of values for the variable n


n_START=-200;
n_END=200;
% Calculate the midpoint of the range (including zero)
n_ZERO=(abs(n_START)+abs(n_END))/2+1;
% Define the pulse width and calculate half of it
pulse_width=111;
half_pulse_width=fix(pulse_width/2);
% Initialize an array for the unit pulse signal
unit_pulse=zeros(abs(n_START)+abs(n_END)+1,1);
% Set the values corresponding to the pulse width to 1
unit_pulse((n_ZERO-half_pulse_width):(n_ZERO+half_pulse_width))=1;
% Plot the unit pulse using stem with specified attributes
stem(n,unit_pulse,'y',Marker='None',Linewidth=2),grid on
% Label the x-axis, y-axis, and provide a title for the plot
xlabel('n')
ylabel('x(n)')
title('UNIT PULSE')

3
3. Generation of Ramp

% Initialize an array for the unit ramp signal


unit_ramp=zeros(abs(n_START)+abs(n_END)+1,1);
% Set the values corresponding to the unit ramp signal
unit_ramp(1+abs(n_START):abs(n_START)+n_END+1)=(0:n_END)/n_END;
% Plot the unit ramp using stem with specified attributes
stem(n,unit_ramp,'g',Marker='None',LineWidth=2),grid on
% Label the x-axis, y-axis, and provide a title for the plot
xlabel('n')
ylabel('x(n)')
title('UNIT RAMP')

4
4. Bipolar Pulse

% Define the pulse width and calculate half of it


pulse_width=111;
half_pulse_width=fix(pulse_width/2);
% Initialize an array for the bipolar pulse signal
bipolar_pulse=zeros(abs(n_START)+abs(n_END)+1,1);
% Specify the duty cycle for the bipolar pulse
dutycycle=0.5;
% Define the index range for the pulse
ind=(n_ZERO-half_pulse_width):(n_ZERO+half_pulse_width);
% Calculate the length of the positive part of the pulse
positiveLen=fix(length(ind)*dutycycle);
% Set values for the positive and negative parts of the pulse
bipolar_pulse(ind(1:positiveLen+1))=1;
bipolar_pulse(ind((positiveLen+2):end))=-1;
% Plot the bipolar pulse using stem plot with specified attributes
stem(n,bipolar_pulse,'m',Marker='None',LineWidth=2),grid on
% Label the x-axis, y-axis, and provide a title for the plot
xlabel('n')
ylabel('x(n)')
title('BIPOLAR PULSE')

5
5. Triangular Signal

% Initialize an array for the triangular signal


tri_signal=zeros(abs(n_START)+abs(n_END)+1,1);
sig_width=111;
% Define the signal width and calculate half of it
half_sig_width=fix(sig_width/2);
% Define the index range for the triangular signal
ind=(n_ZERO-half_sig_width):(n_ZERO+half_sig_width);
% Set values for the ascending and descending parts of the triangular signal
tri_signal(ind(1:half_sig_width))=1:half_sig_width;
tri_signal(ind((half_sig_width+1):end))=(half_sig_width+1):-1:1;
% Plot the triangular signal using stem plot with specified attributes
stem(n,tri_signal,'k',Marker='none',LineWidth=2),grid on
% Label the x-axis, y-axis, and provide a title for the plot
xlabel('n')
ylabel('x(n)')
title('TRIANGULAR SIGNAL')

6
6. Sinusoidal Signal

% Clear the current axis


cla
% Define the values for the variable n
n=0:50;
% Define the frequency and sampling frequency
f=100;
fs=5000;
% Generate a sinusoidal signal using the given parameters
signal=sin(2*pi*(f/fs)*n);
% Plot the sinusoidal signal using stem with specified attributes
stem(n,signal,'b',Marker='None',LineWidth=2),grid on
% Label the x-axis, y-axis, and provide a title for the plot
xlabel('n')
ylabel('x(n)')
title('SINUSOIDAL SIGNAL')
% Hold the current plot to overlay another plot
hold on
% Overlay the sinusoidal signal with a green dashed line
plot(n,signal,'g--')

7
7. Composite Sinusoidal Signal

% Clear the current axis


cla
% Define the values for the variable n
n=0:300;
% Define the frequencies and sampling frequency
f1=50;f2=200;f3=300;
fs=5000;
% Generate a composite sinusoidal signal using the given frequencies
signal=sin(2*pi*(f1/fs)*n+0.5*sin(2*pi*(f2/fs)*n)+0.75*sin(2*pi*(f3/fs)*n));
% Plot the composite sinusoidal signal using stem plot with specified attributes
stem(n,signal,'b',Marker='None',LineWidth=2),grid on
% Label the x-axis, y-axis, and provide a title for the plot
xlabel('n')
ylabel('x(n)')
title('COMPOSITE SINUSOIDAL SIGNAL')
% Hold the current plot to overlay another plot
hold on
% Overlay the composite sinusoidal signal with a red dashed line

plot(n,signal,'r--')

8
RESULT
The MATLAB program to generate waveforms were executed and obtained output waveforms

9
Experiment No:2

VERIFICATION OF PROPERTIES OF DFT


Date: 11-10-2023

Aim

Generate and appreciate a DFT matrix

1. Write a function that returns the N point DFT matrix for for a given N

2. Plot its real and imaginary parts of as images for N=16,N=64,N=1024

3. Compute the DFTs of 16 point, 64 point and 1024 point random sequences using the above matrices N=16:X=

4. Compute the DFTs of 16 point,64 point,1024 point sinusoidal sequences using the above matrices.

5. Observe the time of computataion of DFT for N= for 2<= <=13

6. Use some iterations to plot the times of computation against . Plot and understand this curve. plot the times
of computation for the FFT function over this curve and appreciate the computational saving with FFT.

Theory

Fourier Transform

A Fourier Transform(FT) is an integral transform that converts a function in to a form that describes the
frequencies present in the original function .The output of the transform is a complex-valued.The Fourier
transform of a function (here a signal) is a complex-valued function representing the complex sinusoids out
of which the original function might be reconstructed. For each frequency, the magnitude of the complex value
(modulus) represents the amplitude of a constituent complex sinusoid with that frequency, and the argument of
the complex value represents that complex sinusoid’s phase offset.

X( )=

Where 0≤k≤N-1

Discrete Fourier Transform

Discrete Fourier Transform (DFT) is used to represent the finite duration frequencies. DFT of a discrete
sequence x(n) is obtained by performing sampling operations in both time domain and frequency domain. It
is the frequency domain representation of a discrete digital signal. The DFT of a sequence x (n) of length N is
given by the following equation :

X(k)=

Where 0≤k≤N-1

10
The inverse DFT allows us to recover the sequence x(n) from the frequency samples. The equation is given by :

x(n)=

Where 0≤n≤N-1

Fast Fourier Transform

The most common tools used to perform Fourier analysis and synthesis are called the fast Fourier transform
(FFT) and the inverse fast Fourier transform (IFFT). The FFT and IFFT are optimized (very fast) computer-
based algorithms that perform a generalized mathematical process called the discrete Fourier transform (DFT).
The DFT is the actual mathematical transformation that the data go through when converted from one domain
to another (time to frequency). Basically, the DFT is just a slow version of the FFT

The time taken to evaluate a DFT on a digital computer depends principally on the number of multiplications
involved, since these are the slowest operations. With the DFT, this number is directly related to N2(matrix
multiplication of a vector), where N is the length of the transform.

Programs and Observations

1.Write a function that returns the N point DFT matrix for for a given N

2.Plot its real and imaginary parts of as images for N=16,N=64,N=1024

N=16

N=16;
%Create a DFT matrix of order N
W=dftMatrix(N);
%Obtain the real part and imaginary part of DFT matrix
W_real=real(W);
W_img=imag(W);
%Display images with saved colours
figure(1),imagesc(W_real);
%View and set colormap
colormap jet
title('DFT Matrix-Real Part for N=16 ')

11
figure(2),imagesc(W_img);
colormap jet
title('DFT Matrix-Imaginary Part for N=16')

12
N=64

N=64;
W=dftMatrix(N);
W_real=real(W);
W_img=imag(W);
figure(1),imagesc(W_real);
colormap jet
title('DFT Matrix-Real Part for N=64 ')

13
figure(2),imagesc(W_img);
colormap jet
title('DFT Matrix-Imaginary Part for N=64')

14
N=1024;
W=dftMatrix(N);
W_real=real(W);
W_img=imag(W);
figure(1),imagesc(W_real);
colormap jet
title('DFT Matrix-Real Part for N=1024')

15
figure(2),imagesc(W_img);
colormap jet
title('DFT Matrix-Imaginary Part for N=1024')

16
3. Compute the DFTs of 16 point, 64 point and 1024 point random sequences using the above matrices N=16:X=

16 point

N=16;
%Generate a random sequence of order Nx1
x=randn(N,1);
%Find the DFT of x
X=dftMatrix(N)*x;
%plot the spectrum of x

17
figure(3)
stem(x),title('Signal'),xlabel('n'),ylabel('X(n)')

stem(abs(X)),title('Magnitude Spectrum'),xlabel('K'),ylabel('|X(k)|')

18
stem(angle(X)),title('Phase Spectrum Spectrum'),xlabel('K'),ylabel('\angleX(k)')

19
64 point

N=64;
x=randn(N,1);
X=dftMatrix(N)*x;
figure(3)
stem(x),title('Signal'),xlabel('n'),ylabel('X(n)')

20
stem(abs(X)),title('Magnitude Spectrum'),xlabel('K'),ylabel('|X(k)|')

21
stem(angle(X)),title('Phase Spectrum Spectrum'),xlabel('K'),ylabel('\angleX(k)')

22
1024 point

N=1024;
x=randn(N,1);
X=dftMatrix(N)*x;
figure(3)
stem(x,'g'),title('Signal'),xlabel('n'),ylabel('X(n)')

23
stem(abs(X)),title('Magnitude Spectrum'),xlabel('K'),ylabel('|X(k)|')

24
stem(angle(X)),title('Phase Spectrum Spectrum'),xlabel('K'),ylabel('\angleX(k)')

25
4. Compute the DFTs of 16 point,64 point,1024 point sinusoidal sequences using the above matrices.

16 point

N=16;
%Create an N point sine wave
F=100;
Fs=1000;
n=[0:(N-1)];
x=sin(2*pi*(F/Fs)*n);
%Obtain the spectrum of x
X=dftMatrix(N)*x';
%Plot the N point sine wave
stem(x),title('Signal'),xlabel('n'),ylabel('X(n)');
hold on;
plot(x,'g')
hold off

26
stem(abs(X)),title('Magnitude Spectrum'),xlabel('K'),ylabel('|X(k)|')

27
stem(angle(X)),title('Phase Spectrum Spectrum'),xlabel('K'),ylabel('\angleX(k)')

28
64 point

N=64;
F=100;
Fs=1000;
n=[0:(N-1)];
x=sin(2*pi*(F/Fs)*n);
X=dftMatrix(N)*x';
stem(x),title('Signal'),xlabel('n'),ylabel('X(n)')

29
stem(abs(X)),title('Magnitude Spectrum'),xlabel('K'),ylabel('|X(k)|')

30
stem(angle(X)),title('Phase Spectrum Spectrum'),xlabel('K'),ylabel('\angleX(k)')

31
1024 point

N=1024;
F=100;
Fs=1000;
n=[0:(N-1)];
x=sin(2*pi*(F/Fs)*n);
X=dftMatrix(N)*x';
stem(x),title('Signal'),xlabel('n'),ylabel('X(n)')

32
stem(abs(X)),title('Magnitude Spectrum'),xlabel('K'),ylabel('|X(k)|')

33
stem(angle(X)),title('Phase Spectrum Spectrum'),xlabel('K'),ylabel('\angleX(k)')

34
5. Observe the time of computataion of DFT for N= for 2<= <=13

%create an undefined array time_DFT and time_FFT


time_DFT=[];
%Find the computational time using user defined function
%store the computational time in time_DFT
for gamma =2:13
N=2^gamma;
x=randn(N,1);
tStart=cputime;
X=dftMatrix(N)*x;
time_DFT=[time_DFT,(cputime-tStart)];
end
time_DFT
time_DFT = 1×12

35
0 0 0 0 0 0 0.0156 0.0312

time_FFT=[];
%Find the computational time using inbuilt function
%store the computational time in time_FFT
for gamma =2:13
N=2^gamma;
x=randn(N,1);
tStart=cputime;
X=fft(x);
time_FFT=[time_FFT,(cputime-tStart)];
end
time_FFT
time_FFT = 1×12
0.1406 0 0 0 0 0 0 0

6. Use some iterations to plot the times of computation against . Plot and understand this curve. plot the times
of computation for the FFT function over this curve and appreciate the computational saving with FFT.

%Plot the comutational time taken by inbuilt and user defined function
gamma=2:13;
plot(gamma,time_DFT,'--')
hold on
plot(gamma,time_FFT)
hold off
legend('DFT','FFT')
xlabel('Gamma')
ylabel('Time of computation')

36
function [W_N]=dftMatrix(N)
W_N=zeros(N);
for n=0:(N-1)
for k=0:(N-1)
W_N(n+1,k+1)=exp(-2*pi*j*k*n/N);
end
end
end

Inference

Implemented a function called dftMatrix(N) to calculate the N point DFT. Using that function visualised the real
and imaginary parts of DFT matrices for N=16, N=64 ,and N=1024. Along with that computed the DFTs of
randomly generated sequences, sinusoidal sequences and observed the time of computations of DFT.

Result

Generated DFT matrices and understood its properties using Matlab and verified the outputs

37
Experiment No:3

CIRCULAR CONVOLUTION
Date: 08/11/2023

Aim

• Implement circular convolution using circular shifting.


• Compute circular convolution using the built-in conv function for erification.
• Implement circular convolution using the DFT and inverse DFT operations.

Theory

Circular convolution is defined for periodic sequences, whereas convolution is defined for aperiodic sequences.
The circular convolution of two N-point periodic sequences x(n) and y(n) is the N-point sequence a(m) = x(n)*
y(n), defined by

a(m)=x(m)*y(m)= ,m=0,1,2,…,N−1

Since a(m + N) = a(m), the sequence a(m) is periodic with period N. Therefore A(k) = DFT[a(m)] has period N
and is determined by A(k) = X(k)Y(k).

1.Write a function that returns the circular convolution of an N1 point sequence and an N2 point
sequence given at the input. The easiest way is to convert a linear convolution into circular convolution
with N=max(N1,N2).

%Clear all existing variables and command window

clear all

%Input signals

x=[1 3 5 7 9];
N=length(x);
h=[1 2 3 4 5];

%Ensure column vectors

x=x(:)
x = 5×1
1
3
5
7
9

h=h(:)

38
h = 5×1
1
2
3
4
5

x1=x;
xc=x;
y=[];

%Circular convolution using shifting method

for i=1:N-1
x=circularShift(x);
xc=[xc x];
end
y=xc*h;
y
y = 5×1
75
85
85
75
55

%Circular convolution using built-in cconv function

y2=cconv(x1,h,N);

%Circular convolution using DFT Method

W=dftMatrix(N);
X=W*x1;
H=W*h;
Y=X.*H;
y3=(1/N)*W'*Y;
y3=real(y3);

%Plotting the results

subplot(3,1,1)
plot(y,'g--')
xlabel('N')
ylabel('convolution')
title('circular convolution')
subplot(3,1,2)
plot(y2,'r--')
xlabel('N')
ylabel('convolution')

39
title('circular convolution')
subplot(3,1,3)
plot(y3,'b--')
xlabel('N')
ylabel('convolution')
title('circular convolution')

% Function for computing circular shift

function [y]=circularShift(x)
N=length(x);
y=x*0;
y(1)=x(N);
for i=1:N-1;
y(i+1)=x(i);
end
end

% Function for DFT Matrix

function[W_N]=dftMatrix(N)
W_N=zeros(N);
for n=0:(N-1)

40
for k=0:(N-1)
W_N(n+1,k+1)=exp(-2*pi*j*k*n/N);
end
end
end

Inference and Output

Implemented circular convolution using circular shifting, as demonstrated in the provided code. Computed
circular convolution using MATLAB's built-in cconv function for verification purposes. Implemented circular
convolution using the Discrete Fourier Transform (DFT) and inverse DFT operations. This involves transforming
the input sequences to the frequency domain performig pointwise multiplication, and then transorming back
to the time domain. Compared the results obtained from circular shifting, the cconv function, and the DFT
methods.

Result

Circular convolution of the sequences ae found and the results are verified in MATLAB.

41
Experiment No:4

PARSEVALS THEOREM
Date: 15/11/2023

Aim:
1. Generate two random complex sequence of 5000 values.

2. Prove the theorem for the above signals

3.Repeat the experiment for composite sine waves

Theory:

Parseval’s theorem :
It is an important theorem used to relate the product or square of functions using their respective Fourier
series components. Theorems like Parseval’s theorem are helpful in signal processing, studying behaviours
of random processes, and relating functions from one domain to another. Parseval’s theorem states that the
integral of the square of its function is equal to the square of the function’s Fourier components. This theorem
is helpful when dealing with signal processing and when observing the behaviour of random processes. When
signals are challenging to process with time as their domain, transforming the domain is the best course of
action so that the values are easier to work with. This is where Fourier transforms and the Parseval’s theorem
enters. Taking a look at the equation of Parseval’s theorem for continuous functions, a signal’s power (or
energy) will be much easier to capitalize on and will provide insight on how these quantities behave through a
different domain, say frequency

Programs and Observations


1. Generate two random complex sequence of 5000 values.

clear all
N=5000;
%to generate N random complex sequence
x1=(randn(N,1)+j*randn(N,1));
x2=(randn(N,1)+j*randn(N,1));

2. Prove the theorem for the above signals

%to verify left-hand side of Parsevals Theorem

42
f=x1'*x2
f = 30.3133 + 93.8837i

%generate a DFT matrix of order N


W=dftMatrix(N);
X1=W*x1;
X2=W*x2;
%to verify right-hand side Parsevals Theorem
f=(X1'*X2)/N
f = 30.3133 + 93.8837i

3. Repeat the experiment for composite sine waves

%generation of composite sine wave


n=0:(N-1);
F1=50;
F2=200;
F3=300;
Fs=5000;
sigt=sin(2*pi*(F1/Fs)*n)+0.5*sin(2*pi*(F2/Fs)*n)+0.5*sin((2*pi*(F3/Fs)*n));
sig1=sigt';
sig2=sig1;
%verification of left- hand side of Parsevals Theorem
sigc=sig1'*sig2
sigc = 3.7500e+03

%verification of right-hand side of Parsevals Theorem


W=dftMatrix(N);
SIG1=W*sig1;
SIG2=W*sig2;
SIGC=(SIG1'*SIG2)/N
SIGC = 3.7500e+03

function[W_N]=dftMatrix(N)
W_N=zeros(N);
for n=0:(N-1)
for k=0:(N-1)
W_N(n+1,k+1)=exp(-2*pi*j*k*n/N);
end
end
end

Inference

43
Generated two random sequences of N values and verified the Parsevals Theorem for the same. Verified the
Parsevals Theorem for two composite sine waves.

Result
Verified the Parsevals Theorem using MATLAB and verified the result.

44
Experiment No:5

OVERLAP AND ADD BLOCK CONVOLUTION


Date:15/11/23

Aim

Evaluate linear convolution using overlap and add method.

Theory

In the overlap add method, the longer sequence is divided into smaller sequences. Then linear convolution of
each section of longer sequence and smaller sequence is performed. The overall output sequence is obtained
by combining the output of the sectioned convolution. Let, N1 = Length of longer sequence N2 = Length of
smaller sequence Let the longer sequence be divided into sections of size N3 samples.

The linear convolution of each section with smaller sequence will produce an output sequence of size N3 +
N2 –1 samples. In this method the last N2 –1 samples of each output sequence overlaps with the first N2 –1
samples of the next section. [i.e., there will be a region of N2 –1 samples over which the output sequence of qth
convolution overlaps the output sequence of (q +1)th convolution]. While combining the output sequences of the
various sectioned convolutions, the corresponding samples of overlapped regions are added and the samples
of non-overlapped regions are retained as such.

Programs and Observations

1. Evaluate linear convolution using overlap and add method.

% Define input sequences


x = [1,2,3,4,5,6,7,8];
h = [1,2,3];

% Perform linear convolution using conv function


linconv(x, h)

45
ans = 10×1
1
4
10
16
22
28
34
40
37
24

% Transpose the result of convolution using the transpose operator (')


conv(x, h)'

ans = 10×1
1
4
10
16
22
28
34
40
37
24

% Reshape input sequences into column vectors


x = x(:);
h = h(:);

% Perform linear convolution using the linconv function


linconv(x, h)
ans = 10×1
1
4
10
16
22
28
34
40
37
24

% Calculate the lengths of input sequences


n1 = length(x);
n2 = length(h);

% Calculate the number of blocks needed for zero-padding


M = ceil(n1/n2);

% Zero-pad the input sequence x


x = [x; zeros(M*n2-n1,1)];

46
% Calculate the length of the resulting convolution
N = M*n2 + n2 - 1;
% Initialize the output sequence y
y = zeros(N,1);

% Iterate through each block and perform linear convolution


for i = 1:M
% Extract the current block from x
x_seg = x(((i-1)*n2+1):i*n2);

% Perform linear convolution on the current block


y_seg = linconv(x_seg, h);

% Create zero-padding for the left and right sides of y_seg


r_zeros = zeros(N - (i-1)*n2 - (2*n2-1), 1);
l_zeros = zeros((i-1)*n2, 1);

% Shift y_seg and add it to the output sequence y


y_shifted = [l_zeros; y_seg; r_zeros];
y = y + y_shifted;
end
y

y = 11×1
1
4
10
16
22
28
34
40
37
24

% Plot the result using bar graph


bar(y)

% Add stem plot of the convolution using conv function for comparison
hold on
stem(conv(x, h))

47
% Function to perform linear convolution

function [y] = linconv(x, h)


n1 = length(x);
n2 = length(h);
N = n1 + n2 - 1;
x = x(:);
h = h(:);
x1 = [x; zeros(N - n1, 1)];
h1 = [h; zeros(N - n2, 1)];
Xc = [x1];
for k = 1:N - 1
x1 = shiftcirc(x1);
Xc = [Xc, x1];
end
y = Xc * h1;
end

% Function to perform circular shift


function [x] = shiftcirc(x)
N = length(x);
t = x;

48
temp = x(N);
for i = 1:(N - 1)
x(i + 1) = t(i);
end
x(1) = temp;
end

Inference

Evaluated the linear convolution using overlap and add method .

Result

Verified the linear convolution using overlap and add method and verified the result.

49
Experiment No:6

OVERLAP AND SAVE BLOCK CONVOLUTION


Date:15/11/2023

Aim

• Evaluate linear convolution using overlap and save method.

Theory

In the overlap save method, the results of linear convolution of the various sections are obtained using circular
convolution. In this method, the longer sequence is divided into smaller sequences. Each section of the longer
sequence and the smaller sequence are converted to the size of the output sequence of sectioned convolution.
The circular convolution of each section of the longer sequence and the smaller sequence is performed. The
overall output sequence is obtained by combining the outputs of the sectioned convolution. Let, N1 = Length of
longer sequence N2 = Length of smaller sequence Let the longer sequence be divided into sections of size N3
samples. Note : Normally the longer sequence is divided into sections of size same as that of smaller sequence.
In the overlap save method, the results of linear convolution are obtained by circular convolution. Hence each
section of longer sequence and the smaller sequence are converted to the size of output sequence of size N3 +
N2 – 1 samples.The smaller sequence is converted to size of N3 + N2 –1 samples, by appending with zeros.

The first N2 –1 samples of a section is appended as last N2 –1 samples of the previous section (i.e., the
overlapping samples are placed at the beginning of the section). The circular convolution of each section will
produce an output sequence of size N3 + N2 –1 samples. In this output the first N2 –1 samples are discarded
and the remaining samples of the output of sectioned convolutions are saved as the overall output sequence.

50
Programs and Observations

1. Evaluate linear convolution using overlap and save method.

% Define input signal x1


x1=[1,2,3,4,5,6,7,8];
x=x1;
% Define filter impulse response h1
h1=[1,2,3];
h=h1;
% Determine lengths of input signal and filter
n1=length(x);
n2=length(h);
% Calculate the number of segments for overlap-add method
M=ceil(n1/n2);
% Calculate the length of circular convolution result
N=((M+1)*n2)-1;
% Calculate the length of circular extension for overlap-add method
L=2*n2-1;

51
% Zero-pad input signal x for circular convolution
x=[zeros(1,L-n2) x zeros(1,L-n2)]
x = 1×12
0 0 1 2 3 4 5 6 7 8 0 0

% Zero-pad filter h for circular convolution


h=[h zeros(1,L-n2)]

h = 1×5
1 2 3 0 0

% Transpose filter h for matrix multiplication


h=h';
% Initialize an empty array for the circular convolution result
y=[];
% Loop over each segment for overlap-add method
for i=1:M
% Extract the current segment of the input signal x
x_seg=x(((n2*i)-(n2-1)):((n2*i)+(n2-1)));
x_seg=x_seg(:);
% Initialize a circular extension array
Xc=x_seg;
% Perform circular shifts and concatenate to the extension array
for k=1:L-1
x_seg=shiftcirc(x_seg);
Xc=[Xc x_seg];
end
% Perform circular convolution for the current segment
y_seg=Xc*h;
y_seg=y_seg';
% Append the result to the overall circular convolution result
y=[y y_seg(n2:end)]
end
y = 1×3
1 4 10
y = 1×6
1 4 10 16 22 28
y = 1×9
1 4 10 16 22 28 34 40 37

% Perform linear convolution using built-in conv function


y=conv(x1,h1)
y = 1×10
1 4 10 16 22 28 34 40 37 24

% Plot the circular convolution result


stem(y)

52
% Function to perform circular shift

function[x]=shiftcirc(x)

N=length(x);

t=x;
temp=x(N);

for i=1:(N-1)
x(i+1)=t(i);

end

x(1)=temp;

end

53
Inference
Evaluated the linear convolution using overlap and save method .
Result
Verified the linear convolution using overlap and save method and verified the result.

54
Experiment No:7

FIR FILTER USING HAMMING WINDOW


Date:22/11/2023

Aim

To design FIR filter using hamming method:

1. Implement a FIR low pass filter having the following specifications:

wp=0.25

ws =0.35

δp=0.0058

δs=0.0032

1. Plot the impulse response of the designed filter.

2. Plot single sided and two sided magnitude and phase spectrum of the designed filter.

Theory

FIR filters are digital filters with finite impulse response. They are also known as non-recursive digital filters as
they do not have the feedback.An FIR filter has two important advantages over an IIR design:

• Firstly, there is no feedback loop in the structure of an FIR filter. Due to not having a feedback loop, an
FIR filter is inherently stable. Meanwhile, for an IIR filter, we need to check the stability.
• Secondly, an FIR filter can provide a linear-phase response. As a matter of fact, a linear-phase response
is the main advantage of an FIR filter over an IIR design otherwise, for the same filtering specifications;
an IIR filter will lead to a lower order.

FIR FILTER DESIGN

An FIR filter is designed by finding the coefficients and filter order that meet certain specifications, which can
be in the time-domain and/or the frequency domain . When a particular frequency response is desired, several
different design methods are common:

1. Window design method

2. Frequency Sampling method

WINDOW DESIGN METHOD

In the window design method, one first designs an ideal IIR filter and then truncates the infinite impulse
response by multiplying it with a finite length window function. The result is a finite impulse response filter
whose frequency response is modified from that of the IIR filter.

Programs and Observations

1. Implement a FIR low pass filter having the following specifications:

55
wp=0.25

ws =0.35

δp=0.0058

δs=0.0032

1. Plot the impulse response of the designed filter.

2. Plot single sided and two sided magnitude and phase spectrum of the designed filter.

% Clear the command window and workspace


clc;
clear all;

% Define parameters
M = 63; % Length of the ideal impulse response
omegaC = 0.3 * pi; % Cutoff frequency in radians
n = 0:M; % Discrete time index
N = 1024; % Number of points for the FFT

% Generate the ideal impulse response for a low-pass filter


hideal = sin(omegaC * (n - 0.5 * M)) ./ (pi * omegaC * (n - 0.5 * M));
hideal(isnan(hideal)) = 1; % Handle the division by zero

% Perform FFT on the ideal impulse response


Hideal = fftshift(fft(hideal, N));
magHideal = 20 * log10(abs(Hideal));
phHideal = unwrap(angle(Hideal));

% Generate the Hamming windowed impulse response


h = hideal .* (0.54 - 0.46 * cos(2 * pi * n / M));

% Perform FFT on the Hamming windowed impulse response


H = fftshift(fft(h, N));
magH = 20 * log10(abs(H));
phH = unwrap(angle(H));
omega = linspace(-1, 1, N);

% Plot the impulse response


subplot(3, 1, 1), plot(n, hideal, 'b', 'LineWidth', 2)
hold on, plot(n, h, 'g', 'LineWidth', 2)
grid on, grid minor, axis tight
title('Impulse Response')
ylabel('h(n)'), xlabel('n')
legend('Rectangular', 'Hamming')

% Plot the magnitude response


subplot(3, 1, 2), plot(omega, magHideal, 'r', 'LineWidth', 2)
hold on, plot(omega, magH, 'g', 'LineWidth', 2)
grid on, grid minor, axis tight

56
title('Magnitude Response')
ylabel('|H(e^{j\omega})|'), xlabel('\omega/\pi')
legend('Rectangular', 'Hamming')

% Plot the phase response


subplot(3, 1, 3), plot(omega, phHideal, 'b', 'LineWidth', 2)
hold on, plot(omega, phH, 'g', 'LineWidth', 2)
grid on, grid minor, axis tight
title('Phase Response')
ylabel('\angle |H(e^{j\omega})|'), xlabel('\omega/\pi')
legend('Rectangular','Hamming')

Inference

Generated a low pass FIR filter using Hamming window method for the following given specifications.Also
plotted the impulse response, single sided and two sided magnitude and phase spectrum of designed filter.

Result

Designed a low pass FIR filter using Hamming window method using MATLAB.

57
ECL 333 Digital Signal Processing Lab

Digital Signal Processor

TMS320C6713

based

Experiments

58
ECL 333 Digital Signal Processing Lab

Introduction to Code Composer Studio


1. Launch Code Composer Studio (CCS) version
5.0.

Figure 4: Selecting project type as ’C6000’


generation devices

5. Ignore Additional Project Settings.

Figure 1: Code Composer Studio Splash Screen

2. Create new CCS Project.

Figure 5: Additional Project Settings - Ignore it

Figure 2: Selecting CCS Project Type 6. Review Project Settings and Click ‘Finish’.

3. Provide an appropriate name for your project.

Figure 3: Entering Project Name as ‘exp2’

Figure 6: Project Settings Summary


4. Select platform and configurations.

59
ECL 333 Digital Signal Processing Lab

7. Create a new Source File (here it is an assembly


code) and add it to the project

Figure 10: The newly created file ‘innerp.asm’ is


listing under the project ‘exp2’

Figure 7: Choosing file type as ‘Source File’ and 11. Type the assembly code and make sure there
adding to project. are no errors highlighted in red colour.

8. Enter details of the new source file.

Figure 11: The assembly code ‘innerp.asm’ of the


project.

Figure 8: Entering details of the new source file 12. Create a new C source file named ‘main.c’ and
add it the project.
9. Provide source file name as ‘innerp.asm’.

Figure 12: Creating new C source file ‘main.c’


Figure 9: Entering source file name as
‘innerp.asm’.
13. Enter the file name as ‘main.c’

10. Verify that the newly created file ‘innerp.asm’ is


listed under project.

60
ECL 333 Digital Signal Processing Lab

Figure 13: Preparing the source file ‘main.c’

14. Enter the C program.

Figure 16: Entering filename for ‘Target


Configuration’ file.

Figure 14: The C program file ‘main.c’ associated 17. Provide ‘innerp.ccxml’ as ‘Target Configuration’
with the project ‘exp2’ filename.

15. To simulate the program, create a ‘Target Con-


figuration’ file and add it to the project.

Figure 17: Creating ‘Target Configuration’ file


named ‘innerp.ccxml’

18. Open the ‘Target Configuration’ file ‘innerp.ccxml’.

Figure 15: Adding a ‘Target Configuration’ file to


project.

16. Provide a meaningful file name for the ‘Target


Configuration’ file

Figure 18: Current files in the project showing


‘innerp.ccxml’.

61
ECL 333 Digital Signal Processing Lab

19. Verify that ‘Texas Instruments Simulator’ is se- 23. Check the console for any errors.
lected as the ‘Connection’

Figure 19: View of the ‘Target Configuration’ file Figure 23: CCS Console to view the status of
‘innerp.ccxml’. compilation and running process.

20. Choose the device as ‘C6713 Device Accurate 24. Make sure that the target file is created. In this
Simulator, Little Endian’. case, it is ‘exp2.out’.

Figure 24: The project is compiled successfully


and the target file ‘exp2.out is ready.
Figure 20: Selecting simulating device type as
‘C6713 Device Accurate Simulator, Little Endian’ 25. To start simulating the programming use the
option: Run→ Debug As→Code Composer
Debug Session.
21. Save the ‘Target Configuration’ file .

Figure 21: Saving the ‘Target Configuration’ file

22. Compile the project through Project → Build


All.

Figure 25: Launching the CCS Debugger for


Simulation.

Figure 22: Compiling the project using the menu: 26. Ensure that a Device Debugging session is started
Project → Build All and it is showing ‘TMS320C6713’ as device.

62
ECL 333 Digital Signal Processing Lab

Figure 26: TMS320C6713 Device Debugging


Session

27. TMS320C6713 Device Debugging Session.

Figure 29: Displaying Console Window

30. Variables associated with programs are observed


in Variables Window
Figure 27: TMS320C6713 Device Debugging
Session of ‘exp2’

28. To view Registers go to Window → Show View


→ Registers

Figure 30: Variable Window

31. The status of a custom variables/expressions can


be observed using Expressions Window

Figure 31: Code Composer Studio Splash Screen

Figure 28: Displaying Register Window 32. A variable ‘y’ associated with ‘main.c’ can be
added here.

29. If console is not visible go to Window → Show


View → Console

Figure 32: Adding a custom variable ‘y’ for


watching it during execution of the program.

33. To execute instruction by instruction and to watch


the status use Run → Step Into

63
ECL 333 Digital Signal Processing Lab

Figure 34: Running a program to a line.

35. The status of variable ‘y’ after execution.

Figure 33: Single Stepping the program

34. To execute the program upto a line use Run →


Run to Line

Figure 35: Value of ‘y’ after execution

36. Output displayed in the ‘Console’.

Figure 36: ‘Console’ after execution.

64
ECL 333 Digital Signal Processing Lab

Experiment #01: Inner Product Computation


Aim
To implement inner product computing program using TMS320C6713.

Assembly Language Program : ‘innerp.asm’

1 .def _innerp ;dot product function


2 _innerp:
3 MVK 8,A1 ;move loop count -->A1
4 ZERO A7 ;init A7 for accumulation
5 loop: LDH *A4++,A2 ;A2=content of x address
6 || LDH *B4++,B2 ;B2=content of y address
7 NOP 4 ;4 delay slots for LDH
8 MPY A2,B2,A3 ;A3 = x * y
9 NOP ;1 delay slot for MPY
10 ADD A3,A7,A7 ;sum of products in A7
11 SUB A1,1,A1 ;decrement loop counter
12 [A1] B loop ;branch back to loop till A1=0
13 NOP 5 ;5 delay slots for branch
14 MV A7,A4 ;A4=result
15 B B3 ;return from func to addr in B3
16 NOP 5 ;5 delay slots for branch
C Program - ‘main.c’

1 #include <stdio.h>
2 main()
3{
4 unsigned int x[]={1,2,3,4,0,0,0,0};
5 unsigned int h[]={1,1,3,4,0,0,0,0};
6 unsigned int *p;
7 int y;
8 y=innerp(x,h);
9 printf("Inner Product: %d\n",y);
10 }
Output
Inner Product: 28

65
ECL 333 Digital Signal Processing Lab

Experiment #02: Convolution (FIR Filtering)


Aim
To implement a program to convolve two sequences using TMS320C6713.

Assembly Language Program : ‘fir.asm’

1 .def _fir
2 Y .int 0,0,0,0,0,0,0,0 ; variabel to store result
3 _fir:
4 MVKL Y,A5 ; point A5 to address of X
5 MVKH Y,A5
6 || MVK 8,B2 ; Count N1+N2-1 in B2
7 || ZERO A0 ; Initialize A0 to zero
8 LL2:
9 ZERO A2 ; Initialize A2 to zero
10 || ZERO A7 ; Initialize A7 to zero
11 ZERO A3 ; Initialize A3 (count) to zero
12 || MV A0,B7 ; Initialize B7 to zero
13 LL1:
14 LDW *A4[A3],A6 ; x[A3] in A6
15 || LDW *B4[B7],B6 ; h[A3] in B6
16 NOP 4 ; Wait
17 ADD A3,1,A3 ; Increment Count
18 NOP 4 ; Wait
19 MPY A6,B6,A7 ; x[i] * h[i]
20 NOP ; Wait
21 ADD A2,A7,A2 ; Add A2 and A7, Store the result in A2
22 CMPLTU 0,B7,B0 ; Compare 0 and B7. If 0 < B7 then
23 ; assign B0=1. Else B0=0.
24 SUB B7,1,B7 ; Decrement B7.
25 [B0] B LL1 ; If B0=1 then branch to step 8.
26 NOP 5 ; Wait
27 STW A2,*A5[A0] ; Store the value of A2 in memory
28 ; location specified by A5+A0
29 ADD A0,1,A0 ; Increment A0.
30 MV A0,B5 ; Move the value of A0 to B5.
31 CMPLT B5,B2,B1 ; Compare B5 and B2. If B5 < B2
32 ; then assign B1=1. Else B1=0
33 [B1] B LL2 ; If B1=1 then branch to step 6.
34 NOP 5 ; Wait
C Program - ‘main.c’

1 #include <stdio.h>
2 main()
3{
4 unsigned int x[]={1,2,3,4,0,0,0,0};
5 unsigned int h[]={1,1,3,4,0,0,0,0};
6 unsigned int *p;
7 int y;

66
ECL 333 Digital Signal Processing Lab

8 int i;
9 fir(x,h);
10 p=(unsigned int *)0x00007920;
11 printf("Result of Convolution\n");
12 for(i=0;i<5;i++)
13 {
14 printf("%d\n",p[i]);
15 }
16
17 }
Output
Result of Convolution
1
3
8
17
21
24
16

67
ECL 333 Digital Signal Processing Lab

Fifth Semester Electronics & Communication Engineering

You might also like