Lab Manual - Signals & System - 21ec44
Lab Manual - Signals & System - 21ec44
Experiment 1
AIM: Generation of the following discrete signals using MATLAB. (i) unit step (ii) unit impulse
(iii) unit ramp (iv) Sinc (v)Gaussian Perform basic operations: time shifting, time scaling, and
time reversal for the above signals and plot.
Objective:
1. To Generate all basic signals and plot the same as a function of time.
2. To plot the 2D and 3D signals such as LIDAR and Image
Theory:
There are several elementary or basic signals which are used to model a large number of physical
signals which occur in nature. These elementary signals are also called Standard Signals. Some
of these signals are described below
That is, u is a function of time t, and u has a value of zero when time is negative and a value of
one when time is positive.
r(t) = t.u(t)
iv) Sinc Pulse:
A sinc function is an even function with a unit area. A sinc pulse passes through zero at all
positive and negative integers (i.e., t=±1,±2,…), but at time t=0, it reaches its maximum of 1.
This is a very desirable property in a pulse, as it helps to avoid intersymbol interference, a major
cause of degradation in digital transmission systems. The product of a sinc function and any
other signal would also guarantee zero crossings at all positive and negative integers.
The normalized sinc function is commonly defined for x ≠ 0 by
v) Gaussian Pulse
In one dimension, the Gaussian function is the probability density function of the normal
distribution,
MATLAB Code:
i) Impulse signal
%Generation of UNIT impulse signal
clc; close all; clear all;
n=-2:1:2;
y=[zeros(1,2),ones(1,1),zeros(1,2)]
figure(1)
stem(n,y);
xlabel("Time ")
ylabel("Amplitude")
title('unit impulse');
ii) %Generation of UNIT step signal
clc; close all; clear all;
n=input('enter the n value');
t=0:1:n-1;
y=ones(1,n);
figure(2)
stem(t,y);
title('unit step');
xlabel("Time (sec)")
ylabel("Amplitude")
%rgb2gray
clc; % clear command window
clear all;% clear workspace
close all;% clear all figures
I1=imread('D:\waterlily.jpg');
figure;
imshow(I1);
title('color image');
I2=rgb2gray(I1);
figure;
imshow(I2);
title('Gray image');
subplot(2,2,1);subimage(I1); title('Color Image');
subplot(2,2,2);subimage(I2); title('Gray Image');
Practise Questions:
Write a code in Python to generate all the basic signals and plot the same using appropriate
library functions.
Data sheet
A Problem statement 10
B Design & specifications 10
C Expected output 10
Record
D Simulation/ Conduction of the 15
experiment
E Analysis of the result 15
Viva 40
Total 100
Scale down to 10 marks
Experiment 2
AIM: Perform basic operations: time shifting, time scaling and time reversal for the basic signals
and plot them as a function of time.
Objective:
1. To Perform basic operations on the dependent variable of signals and observe the
behavior of signals for different values of amplitude.
2. To perform basic operations on independent variable of signals as a function of time with
appropriate shifting and scaling.
In this transformation, only the quadrature axis values are modified i.e magnitude of the
signal changes, with no effects on the horizontal axis values or periodicity of signals like.
● Time Shifting
● Time Scaling
● Time Reversal
Time Shifting
A signal x(t) may be shifted in time by replacing the independent variable t by either t−t0 or t+t0 .
Here t0 is called the shifting factor. Shifting in time may result in time delay or time
advancement.
If the independent variable t is replaced by t−t0 , the signal is shifted to the right, and the time
shift results in a delay of the signal by t0 units of time. This type of time shifting is known as
Right side shifting. This can be achieved by adding t0 value to every time instant in signal x(t).
If the independent variable t is replaced by t+t0 , the signal is shifted to the left and the time shift
results in an advancement of the signal by t0 units of time. This type of time shifting is known as
Left side shifting. This can be achieved by subtracting t0 value to every time instant in signal x(t).
Time Scaling
A signal x(t) may be scaled in time by replacing the independent variable t with at. Here ‘a’ is
called the scaling factor. Time scaling may result in signal compression or signal expansion.
If the independent variable t is replaced by at and a>1, the signal is compressed. This can be
achieved by dividing every time instant in signal x(t) by ‘a‘.
If the independent variable t is replaced by at and 0<a<1, the signal is expanded. This can be
achieved by dividing every time instant in signal x(t) by ‘a‘.
Time Reversal
If the independent variable t is replaced by ‘−t’ , this operation is known as time reversal of the
signal about the y-axis or amplitude axis. This can be achieved by taking mirror image of the
signal x(t) about y-axis or by rotating x(t) by 180° about y-axis. Hence, time reversal is known as
folding or reflection.
MATLAB Code:
i) Addition of two signals
t=0:0.01:0.1
f=25;
t1=2*pi*f*t;
x1=sin(t1);
subplot(3,1,1)
plot(t,x1)
title('x1')
xlabel('Time')
ylabel('Amplitude')
grid on;
x2=cos(t1)
subplot(3,1,2)
plot(t,x2)
title('x2')
xlabel('Time')
ylabel('Amplitude')
y=x1+x2
subplot(3,1,3)
plot(t,y)
title('Addition of 2 signals y= x1+x2')
xlabel('Time')
ylabel('Amplitude')
iii)Time reversal
t=0:10;
x=[0 1 2 3 4 -5 -6 -7 -8 -9 -10];
subplot(2,1,1)
stem(t,x)
title('Simple Signal')
xlabel('Time')
ylabel('Amplitude')
grid on;
y=fliplr(x);
subplot(2,1,2)
stem(t,y)
title('Reflected Signal')
xlabel('Time')
ylabel('Amplitude')
grid on;
Practise Questions:
Write the MATLAB Code to sketch the following signals and verify the same using analytical
method
a. r(t+2)-r(t+1)-r(t-2)+r(t-3)
b. u(n+2)-3u(n-1)+2u(n-5)
Data sheet
A Problem statement 10
B Design & specifications 10
C Expected output 10
Record
D Simulation/ Conduction of the 15
experiment
E Analysis of the result 15
Viva 40
Total 100
Scale down to 10 marks
Experiment 3
AIM: To write a MATLAB program to FT of basic signals. Also plot its magnitude and phase
spectrum.
Objective:
1. To Generate basic signals Such as sinusoidal,rectangular and triangular signals
2. To find their fourier transform and plot its magnitude and phase spectrum.
Theory:
The generalization of the complex Fourier series is known as the Fourier transform. The term
“Fourier transform” can be used in the mathematical function, and it is also used in the
representation of the frequency domain. The Fourier transform helps to extend the Fourier series
to the non-periodic functions, which helps us to view any functions in terms of the sum of simple
sinusoids.
Practice Questions:
1. Generate triangular signal and plot its magnitude and phase response
2. Generate an impulse signal(like siren/Hammer/Buzzer)and plot its magnitude and phase
response.
AIM: To write a MATLAB program for calculating DFT and IDFT discrete time sequences
using analytical calculation and inbuilt function.
Objective:
2. To Generate basic signals to find frequency response..
3. To plot its magnitude and phase spectrum.
Theory:
DFT
For a sequence x[n] with length N ( x[n] for n=0,1, 2, ..., N-1), the discrete-time Fourier
transform is
The usually considered frequency interval is (-π , π ). There are infinitely many points in the
interval. If x[n] has N points, we compute N equally spaced ω in the interval (-π , π ). That is,
we sample using the frequencies.
Inverse DFT
The DFT values (X(K), 0 ≤ k ≤ N – 1), uniquely define the sequence x[n] through the inverse
DFT formula (IDFT) x(n) = IDFT {X(k)} , 0≤N≤n–1
The above equation is known as the Synthesis equation.
Matlab Program:
(iii) n=100
Matlab code:
n2=[0:1:99];
x2=[x(1:1:10) zeros(1,90)];
y2=fft(x2);
mag_y2=abs(y2);
phase_y2=angle(y2);
figure(2);
subplot(3,1,1);
stem(n2,x2);
xlabel('n--->');
title('Input samples');
subplot(3,1,2);
F=2*pi*n2/100;
stem(F/pi,mag_y2);
xlabel('Frequency in units of Pi');
title('Magnitude plot');
X2=ifft(y2);
subplot(3,1,3);
stem(F/pi,phase_y2);
xlabel('Frequency in units of Pi'); DFT with 10 samples of the signal + padding with zeros
title('phase plot');
% 100 samples
n3=[0:1:99];
x=cos(0.48*pi*n3)+cos(0.52*pi*n3);
x3=x(1:1:100);
y3=fft(x3);
mag_y3=abs(y3);
phase_y3=angle(y3);
figure(3);
subplot(3,1,1);
stem(n3,x3);
xlabel('n--->');
title('Input samples');
subplot(3,1,2);
F=2*pi*n3/100;
%F1=2*pi*[-50:1:49]/100;
stem(F/pi,mag_y3);
xlabel('Frequency in units of Pi');
title('Magnitude plot');
X3=ifft(y3);
subplot(3,1,3);
stem(F/pi,phase_y3);
xlabel('Frequency in units of Pi');
title('phase plot');
Practice Questions:
1. Given x(n) = [1,2,3,4] , obtain DFT and IDFT using formula. Plot magnitude and phase
plot.
2. Record speech signal and plot FFT.
AIM: To write a Python program for linear and circular convolution of two discrete time
sequences. Plot all the sequences and verify the result by analytical calculation.
Objective:
1. To convolve two discrete sequences using linear convolution
2. To convolve two discrete sequences using circular convolution
Theory:
Linear Convolution:
For a system with the impulse response h[n] the output for any arbitrary input x[n] is given by
convolution defined as,
Circular convolution:
It is periodic convolution. and are the two finite duration sequences of length N, the circular
convolution between though sequence is given by
The linear convolution of an N-point vector, x, and a L-point vector, y, has length N+L-1.For the
circular convolution of x and y to be equivalent, you must pad the vectors with zeros to length at
least N+L-1 before you take the DFT. After you invert the product of the DFTs, retain only the
first N+L-1 elements.
Python Code
Linear Convolution
(a) #Program to perform linear convolution
import numpy as np
import scipy as sy
from matplotlib import pyplot as plt
#impulse response
h = [1,2,3,3,2,1];
#input response
x = [1,2,3,4,5];
N1 = len(x)
N2 = len(h)
N = N1+N2-1
y = np.zeros(N)
x = [[x],[np.zeros(N-N1)]]
h = [h,np.zeros(N-N2)]
#Linear convolution using built-in function in NumPy
y1 = np.convolve(x,h)
m = N-N1
n = N-N2
#Padding zeros to x and h to make their length to N
x =np.pad(x,(0,m),'constant')
h =np.pad(h,(0,n),'constant')
#Linear convolution using convolution sum formula
for n in range (N):
for k in range (N):
if n >= k:
y[n] = y[n]+x[n-k]*h[k]
print('Linear convolution using convolution sum formula output response y =\n',y)
print('Linear convolution using NumPy built-in function output response y=\n',y1)
#RESULTS
Linear convolution using convolution sum formula output response y = [ 1. 4. 10. 19. 30. 36. 35.
26. 14. 5.]
Linear convolution using NumPy built-in function output response y= [ 1 4 10 19 30 36 35 26
14 5]
Circular Convolution
# Python program to compute circular convolution of two arrays
MAX_SIZE = 10;
# Function to find circular convolution
def convolution(x, h, n, m):
row_vec = [0] * MAX_SIZE;
col_vec = [0] * MAX_SIZE;
out = [0] * MAX_SIZE;
circular_shift_mat = [[0 for i in range(MAX_SIZE)]
for j in range(MAX_SIZE)] ;
# Finding the maximum size between the two input sequence sizes
if(n > m ):
maxSize = n;
else:
maxSize = m;
# Copying elements of x to row_vec and padding zeros if size of x < maxSize
for i in range(maxSize):
if (i >= n):
row_vec[i] = 0;
else:
row_vec[i] = x[i];
# Copying elements of h to col_vec and padding zeros if size of h is less than maxSize
for i in range(maxSize):
if (i >= m):
col_vec[i] = 0;
else:
col_vec[i] = h[i];
# Generating 2D matrix of circularly shifted elements
k = 0;
d = 0;
for i in range(maxSize):
curIndex = k - d;
for j in range(maxSize):
circular_shift_mat[j][i] = \
row_vec[curIndex % maxSize];
curIndex += 1;
k = maxSize;
d += 1;
# Computing result by matrix multiplication and printing results
for i in range(maxSize):
for j in range(maxSize):
out[i] += circular_shift_mat[i][j] * \
col_vec[j];
print(out[i], end = " ");
# Driver program
if __name__ == '__main__':
x = [ 5, 7, 3, 2 ];
n = len(x);
h = [ 5, 7, 3, 2 ];
# h=[5, 7, 3, 2];
m = len(h);
convolution(x, h, n, m);
# Result of circular convolution is [62 82 83 62]
Practice question:
1. Generate a sinusoidal signal using python and plot the same
2. Generate two sinusoidal signals having 400Hz and 4000Hz using python and plot the
mix of two signals.
AIM: To write a Python program for circular correlation of two discrete time sequences. Plot all
the sequences and verify the result by analytical calculation.
Objective:
1. To do the autocorrelation of a discrete sequence
2. To do the cross correlation of two discrete sequences
Theory
Python Code
(a) #Program to perform auto correlation
import numpy as np
import scipy as sy
from matplotlib import pyplot as plt
#input response
#x = [1,0,0,2]
x = eval(input('Enter the input sequence x[n]='))
N1 = len(x)
h=np.zeros(N1)
N2 = len(x)
N = N1+N2-1
y = np.zeros(N)
for i in range (N1):
h[N1-1-i]=x[i]
#Correlation using Linear convolution built-in function in NumPy
y1 = np.convolve(x,h)
#Correlation using Correlation built-in function in NumPY
y2 = np.correlate(x,x,'full')
print('Auto correlation using NumPy Linear convolution built-in function -correlation result
y=\n',y1)
print('Auto correlation using NumPy correlation built-in function - correlation result y=\n',y2)
m = N-N1
n = N-N2
#Padding zeros to x and h to make their length to N
x =np.pad(x,(0,m),'constant')
h =np.pad(h,(0,n),'constant')
#correlation using formula
for n in range (N):
for k in range (N):
if n >= k:
y[n] = y[n]+x[n-k]*h[k]
print('correlation using formula - correlation result y =\n',y)
#RESULT
Auto correlation using NumPy Linear convolution built-in function -correlation result y=
[2. 0. 0. 5. 0. 0. 2.]
Auto correlation using NumPy correlation built-in function - correlation result y= [2 0 0 5 0 0 2]
correlation using formula - correlation result y =[2. 0. 0. 5. 0. 0. 2.]
#RESULT
Enter the input sequence x[n]=[1,2,1,1]
Enter the input sequence h[n]=[1,1,2,1]
Auto correlation using NumPy Linear convolution built-in function -correlation result y=
[1 3 4 5 4 2 1]
Practice question:
Data sheet
A Problem statement 10
B Design & specifications 10
C Expected output 10
Record
D Simulation/ Conduction of the 15
experiment
E Analysis of the result 15
Viva 40
Total 100
Scale down to 10 marks
Experiment 7
AIM: To write a python code to extract features in time domain for any signal.
Objective:
1. Extract time domain feature from any audio signal (single tone/multitone)
Theory
4.MFCC
# MFCC component
mfccs = librosa.feature.mfcc(x, sr=sr)
print(mfccs.shape)
#Displaying the MFCCs:
librosa.display.specshow(mfccs, sr=sr, x_axis='time')
#The first value represents the number of mfccs calculated and another value represents a
number of
5. Chroma: We can use Chroma feature visualization to know how dominant the
characteristics of a certain pitch {C, C♯, D, D♯, E, F, F♯, G, G♯, A, A♯, B} is present in the
sampled frame.
x, sr = librosa.load('/content/drive/MyDrive/Colab Notebooks/training datasets/cars014.wav')
hop_length = 512
chromagram = librosa.feature.chroma_stft(x, sr=sr, hop_length=hop_length)
fig, ax = plt.subplots(figsize=(15, 3))
img = librosa.display.specshow(chromagram, x_axis='time', y_axis='chroma',
hop_length=hop_length, cmap='coolwarm')
fig.colorbar(img, ax=ax)
6.Tempo refers to the speed of an audio piece, which is usually measured in beats per
minute (bpm) units. Upbeat music like hip-hop, techno, or rock usually has a higher tempo
compared to classical music, and hence tempogram feature can be useful for music genre
classification.
y, sr = librosa.load('/content/drive/MyDrive/Colab Notebooks/training datasets/cars014.wav')
hop_length = 512# Compute local onset autocorrelation
oenv = librosa.onset.onset_strength(y=y, sr=sr, hop_length=hop_length)
times = librosa.times_like(oenv, sr=sr, hop_length=hop_length)
tempogram = librosa.feature.tempogram(onset_envelope=oenv, sr=sr, hop_length=hop_length)#
Estimate the global tempo for display purposes
tempo = librosa.beat.tempo(onset_envelope=oenv, sr=sr,hop_length=hop_length)
Data sheet
A Problem statement 10
B Design & specifications 10
C Expected output 10
Record
D Simulation/ Conduction of the 15
experiment
E Analysis of the result 15
Viva 40
Total 100
Scale down to 10 marks
Experiment 8
AIM: To write a python code to extract features in frequency domain for any signal.
Objective :
1. Extract frequency domain feature from any audio signal (single tone/multitone)
import librosa #librosa is a Python package for music and audio processing
import librosa.display #
import IPython.display as ipd #to play the audio signal
import matplotlib.pyplot as plt #plot the audio signal in time domain
ipd.Audio('/content/drive/MyDrive/ColabNotebooks/trainingdatasets/cars001.wav) #load a local
WAV file
audio_path=('/content/drive/MyDrive/ColabNotebooks/trainingdatasets/cars001.wav')
x , sr = librosa.load(audio_path) # 22050Hz
import numpy as np
import sklearn
import scipy
freqs = np.fft.fftfreq(x.size)
mean=np.mean(freqs) #average of values of the given samples,Measure of central tendency –
mean – the first moment
std = np.std(freqs) #Measure of dispersion – variance – the second moment:
maxv = np.amax(freqs)
minv = np.amin(freqs)
median = np.median(freqs)
skew = scipy.stats.skew(freqs) #Higher order moments – skewness and kurtosis:
kurt = scipy.stats.kurtosis(freqs) # identify anomalies and outliers in many signal processing
applications.
q1 = np.quantile(freqs, 0.25)
q3 = np.quantile(freqs, 0.75)
mode = scipy.stats.mode(freqs)[0][0]
iqr = scipy.stats.iqr(freqs)
Data sheet
A Problem statement 10
B Design & specifications 10
C Expected output 10
Record
D Simulation/ Conduction of the 15
experiment
E Analysis of the result 15
Viva 40
Total 100
Scale down to 10 marks
Experiment 9
Objective:
1. Designing Amplitude modulator and demodulator using Simulink
2. Understanding the waveforms of modulated and demodulated signals.
3. Observing the effects of the percent of modulation
Theory:
Modulation is a process by which some characteristic of a carrier is varied in accordance with a
modulating wave. The message signal is referred to as the modulating wave and the result of the
modulation process is referred to as the modulated wave.
Amplitude Modulation:
where is called the amplitude sensitivity of the modulator. The envelope of the modulated signal
is given by,
Percentage Modulation:
> 1, then the percentage modulation is in excess of 100%. In first case will have one to
one correspondence where as in the second case, modulated wave is said to suffer from envelope
distortion and the wave is said to be over-modulated.
Conventional AM in Simulink
Procedure:
● Type Simulink in the Matlab Command Window to open a Simulink Library Browser
● Go to Signal Processing Blockset -> Signal Processing Sources
● Choose Sine wave as source. Right click on it and select add to untitled.
File -> save as -> give file name and save it with .mdl extension For ex: Std_AM.mdl
In this experiment Simulink is used to generate a Conventional Amplitude Modulator
(Transmitter and receiver). Construct the model as shown in the figure below by searching
each block in a Simulink Library Browser.
Input Parameters:
(a) Sine wave
Amplitude: 1 V
Frequency: 4 Hz
Phase offset: 0 radians
Sample mode: Discrete
Output complexity: Real
Computation method: Trigonometric fcn
Sample time: 1/500
Samples per frame: 1
(b) Constant
Constant value: 1
(d) Add
List of signs: ++
(h) Scope
Go to Settings, then click on History and Uncheck the limit data points to last
Run time : 4sec
Waveforms:
Practice Questions:
1. AM modulation and Demodulation using MATLAB also perform frequency domain
analysis
2. To Develop a Simulink model to demonstrate any variant Amplitude modulation and
Demodulation.
Sl. No Criteria Max Marks Marks obtained
Data sheet
A Problem statement 10
B Design & specifications 10
C Expected output 10
Record
D Simulation/ Conduction of the 15
experiment
E Analysis of the result 15
Viva 40
Total 100
Scale down to 10 marks
Experiment 10
AIM: To write a python Code to classify two signals using various features.
Data sheet
A Problem statement 10
B Design & specifications 10
C Expected output 10
Record
D Simulation/ Conduction of the 15
experiment
E Analysis of the result 15
Viva 40
Total 100
Scale down to 10 marks
Experiment 11