0% found this document useful (0 votes)
29 views29 pages

DSP Lab

Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
Download as docx, pdf, or txt
0% found this document useful (0 votes)
29 views29 pages

DSP Lab

Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
Download as docx, pdf, or txt
Download as docx, pdf, or txt
You are on page 1/ 29

DIGITAL SIGNAL PROCESSING

PRACTICAL FILE (EC-317)

SUBMITTED BY
NAME: ROSHNI GHAI
ROLL NO: 21BEC037
BRANCH: ECE (4 YEAR)
SECTION: A
SEMESTER: 5
21BEC037 ROSHNI GHAI

INDEX
S NO. EXPERIMENT DATE PAGE SIGNATURE
NO.
1. Introduction to Matlab 2.8.23 3-8
To plot basic signals on Matlab
2. 2.8.23 9-15
and observe their waveform.
3. Write a Matlab program to find 9.8.23 16-19
linear convolution of two
discrete signals.
Write a MATLAB program to
4. 23.8.23 20-25
find the correlation of two
signals.
Write a MATLAB program to
5. 6.9.23 26-28
find the circular convolution of
two signals.

2
21BEC037 ROSHNI GHAI

INTRODUCTION TO MATLAB
MATLAB (Matrix Laboratory) is a powerful and widely-used programming language
and interactive computing environment that is specifically designed for numerical
computing, data analysis, visualization, and algorithm development. It was created by
MathWorks and first released in 1984. Over the years, MATLAB has evolved into a
versatile tool used across various industries, including engineering, mathematics,
science, finance, and academia.

MATLAB is a software package for high-performance language for technical


computing. It integrates computation, visualization, and programming in an easy-to-
use environment where problems and solutions are expressed in familiar
mathematical notation.

TYPICAL USES INCLUDE THE FOLLOWING:


 Math and computation
 Algorithm development
 Data acquisition
 Modeling, simulation, and prototyping
 Data analysis, exploration, and visualization
 Scientific and engineering graphics
 Application development, including graphical user interface building

The name MATLAB stands for matrix laboratory. MATLAB was originally written
to provide easy access to matrix software developed by the LINPACK and EISPACK
projects. Today, MATLAB engines incorporate the LAPACK and BLAS libraries,
embedding the state of the art in software for matrix computation.

MATLAB has evolved over a period of years with input from many users. In
university environments, it is the standard instructional tool for introductory and
advanced courses in mathematics, engineering, and science. In industry, MATLAB is
the tool of choice for high-productivity research, development, and analysis.

MATLAB features a family of add-on application-specific solutions called toolboxes.


Very important to most users of MATLAB, toolboxes allow learning and applying
specialized technology. Toolboxes are comprehensive collections of MATLAB
functions (M-files) that extend the MATLAB environment to solve particular classes
of problems. Areas in which toolboxes are available include Image processing, signal
processing, control systems, neural networks, fuzzy logic, wavelets, simulation, and
many others.
THE MAIN FEATURES OF MATLAB
 Advance algorithm for high performance numerical computation , especially in the
Field matrix algebra
3
21BEC037 ROSHNI GHAI

 A large collection of predefined mathematical functions and the ability to


define one’s own functions.
 Two-and three dimensional graphics for plotting and displaying data
 A complete online help system
 Powerful, matrix or vector oriented high level programming language for
individual applications.
 Toolboxes available for solving advanced problems in several application
areas

In the domain of Digital Signal Processing (DSP), MATLAB's capabilities are


particularly valuable. DSP involves the manipulation and analysis of signals to
extract useful information or enhance specific aspects of the signal. MATLAB's
powerful built-in functions and toolboxes cater to the needs of DSP engineers and
researchers. It facilitates signal processing tasks such as filtering, Fourier
analysis, spectral analysis, signal synthesis, and waveform generation. Engineers
can design and implement various filters like low-pass, high-pass, bandpass, and
notch filters using MATLAB's intuitive interface. Additionally, MATLAB's
support for vectorized operations enables users to process large datasets
efficiently, making it an ideal platform for exploring and experimenting with
various DSP algorithms and techniques. Its vast library of functions and
visualization capabilities further enhance the DSP workflow, allowing users to
gain valuable insights into the behavior of signals and the effectiveness of their
processing techniques.

VARIOUS WINDOWS OF MATLAB :

• Command Window - to execute commands in the MATLAB environment

• Current Directory Window - to quickly access files on the MATLAB path

• Figure Window - to display graphical output from MATLAB code

• Workspace Window - to view variable definitions and variable memory


allocations

• Command History Window - displays all commands issued in MATLAB


since the last session (good for learning and verification)

4
21BEC037 ROSHNI GHAI

BASIC COMMANDS OF MATLAB:

1. disp('Hello!');: Displays the specified message in the command window.


2. variable_name = value; : Assigns the given value to the specified variable.
3. Arithmetic Operations:
 Addition: result = num1 + num2;
 Subtraction: result = num1 - num2;
 Multiplication: result = num1 * num2;
 Division: result = num1 / num2;
 Exponentiation: result = base ^ exponent;
4. Creating Vectors and Matrices:
 Vectors: vec = [1, 2, 3];
 Matrices: mat = [1, 2; 3, 4];
5. Accessing Elements:
 element = mat(row, col);: Retrieves the element at the specified row
and column in a matrix.
6. Defining and Calling Functions:
 Defining:
function output = myFunction(input)
% Function body
output = input * 2;
end
 Calling: result = myFunction(value);

7. Basic Plotting:

5
21BEC037 ROSHNI GHAI

Generating x values: x = linspace(0, 2*pi, 100);


 Generating y values: y = sin(x);
 Creating a plot: plot(x, y);
 Adding labels and title: xlabel('X-axis'); ylabel('Y-axis'); title('Sine
Wave');
8. Conditional Statements:
if condition
% Statements when condition is true
elseif another_condition
% Statements when another_condition is true
else
% Statements when no condition is true
end
9. Loops:
 For loop:
for i = 1:5
% Loop body
End
 While Loop
while condition
% Loop body
end
10.Logical Operations:
 ==, ~=: Equal to, not equal to
 >, <, >=, <=: Comparison operators
 &&: Logical AND
 ||: Logical OR
 ~: Logical NOT
11.Getting Help:
 help command_name;: Provides help for a specific command.
 doc command_name;: Opens the documentation for a command.

ADVANTAGES OF MATLAB

1. Ease of Use: MATLAB's syntax is designed to be intuitive and easy to


learn, especially for individuals with a background in mathematics and
engineering. Its interactive interface and extensive documentation make it
beginner-friendly.
2. Matrix Operations: MATLAB's core strength lies in its ability to perform
matrix and array operations efficiently. This is particularly useful for tasks
involving linear algebra, signal processing, and image analysis.
3. Built-in Functions: MATLAB comes with a vast collection of built-in

6
21BEC037 ROSHNI GHAI

functions and toolboxes for various domains such as signal processing,


optimization, control systems, statistics, and more. These functions save
time by providing ready-made solutions for common tasks.
4. Visualization: MATLAB provides powerful plotting and visualization
tools that allow users to create high-quality graphs, charts, and visual
representations of data. This is valuable for data analysis and presentations.
5. Data Analysis and Statistics: MATLAB offers comprehensive tools for
data analysis, including statistical functions, data fitting, regression
analysis, and hypothesis testing. It's widely used in research and academic
settings for analyzing experimental data.
6. Simulations and Modeling: Engineers and scientists use MATLAB for
simulations and modeling tasks. It can simulate complex systems, analyze
their behavior, and aid in making informed decisions based on the
simulation results.
7. Interdisciplinary Applications: MATLAB is used across various
disciplines, from engineering and physics to finance and biology. Its
versatility makes it a valuable tool for researchers and professionals in
different fields.
8. Community and Support: MATLAB has a large user community, which
means you can find help, resources, and forums online. This community
support can be crucial when you encounter challenges or need to learn new
techniques.
9. Integration with Other Languages: MATLAB can integrate with other
programming languages like C, C++, and Java. This is useful when you
need to leverage existing codebases or use specialized libraries.
10.Graphical User Interface (GUI) Design: MATLAB allows you to create
custom graphical user interfaces (GUIs) without extensive coding. This is
helpful for building interactive applications or tools.
11.Education and Research: MATLAB is widely used in academic and
research environments. It's often taught in universities, making it a valuable
skill for students pursuing careers in technical fields.
12.Parallel and Distributed Computing: MATLAB supports parallel and
distributed computing, allowing you to leverage multiple processors or
computers to speed up computations for large datasets or complex
simulations.
13.Deployment: MATLAB code can be compiled into standalone
applications, making it possible to distribute your work without requiring
recipients to have MATLAB installed.

7
21BEC037 ROSHNI GHAI

DISADVANTAGES OF MATLAB:

1. Proprietary Nature: MATLAB is not open-source, which means you


don't have access to the source code. This can limit your ability to
customize or modify the software to suit your specific needs.
2. Performance for Large Datasets: While MATLAB is efficient for many
tasks, its performance can degrade when dealing with very large datasets or
complex simulations. Other languages like Python offer better performance
optimization tools.
3. Memory Usage: MATLAB can consume significant memory, particularly
when dealing with large arrays or matrices. This can lead to slower
performance and potential memory-related issues.
4. Limited Multithreading: While MATLAB supports parallel computing,
its multithreading capabilities are somewhat limited compared to other
languages and frameworks. This can affect the efficiency of computations
on multi-core processors.
5. Steep Learning Curve for Advanced Features: While basic usage is
straightforward, mastering advanced features and techniques in MATLAB,
such as object-oriented programming or advanced toolboxes, can require a
significant learning curve.
6. Limited Integration with Non-MATLAB Tools: While MATLAB can
integrate with other programming languages, it may not seamlessly work
with all software tools or libraries, which can limit interoperability in
certain cases.

In conclusion, MATLAB is a powerful and versatile tool for numerical


computing, data analysis, and algorithm development. Its efficient matrix
handling capabilities, user-friendly interface, extensive visualization tools, and
vast library of functions make it an essential resource for engineers, scientists,
and researchers worldwide. As we delve further into the world of MATLAB, we
will explore its features, applications, and advanced functionalities that make it an
indispensable tool for solving complex problems and pushing the boundaries of
scientific understanding.

8
21BEC037 ROSHNI GHAI

EXPERIMENT 1
AIM: To plot basic signals on Matlab and observe their waveform.

THEORY: Discrete-time signals in MATLAB are representations of


sequences of values at discrete points in time. These signals are often stored as
arrays or vectors, with each element corresponding to a specific time index.
MATLAB provides tools to create, analyze, and manipulate these signals,
allowing for operations such as plotting, convolution, and filtering. The discrete
nature of these signals makes them suitable for digital signal processing tasks
like sampling, quantization, and various forms of analysis in both the time and
frequency domains. The basic signals are as follows:

1. Unit Step Signal: The unit step signal, also known as the Heaviside
step function, is a fundamental signal in both continuous-time and discrete-
time signal processing. It has a value of 0 for negative time indices and a
value of 1 for non-negative time indices. It is denoted as u(t) or u[n] in the
continuous-time and discrete-time domains respectively
Formulas for the unit step signal:
For continuous-time (analog) domain:
u(t) = {
0, t < 0
1, t >= 0
}
For discrete-time domain:
u[n] = {
0, n < 0
1, n >= 0
}
In these formulas, t represents time in the continuous-time domain, and n
represents time indices in the discrete-time domain.

2. Unit Impulse Signal: The unit impulse signal, also known as the
Dirac delta function, is a theoretical construct used in mathematics and
signal processing to describe an infinitely short and infinitely high pulse.
It's often represented as δ(t) in continuous-time and δ[n] in discrete-time
domains. The unit impulse has the unique property that its integral (or
sum in the discrete case) over the entire domain is equal to 1.

Formulas for the unit impulse signal:

9
21BEC037 ROSHNI GHAI

Continuous-Time (Analog) Domain:

δ(t) = {
∞, t = 0
0, t ≠ 0
}
Discrete-Time Domain:

δ[n] = {
1, n = 0
0, n ≠ 0
}

In these formulas, t represents time in the continuous-time domain, and n


represents time indices in the discrete-time domain.

3. Ramp Signal
A ramp signal is a type of signal that increases linearly with time in the
continuous-time domain or with time indices in the discrete-time domain.
It's a simple and often used signal in various applications such as control
systems, signal processing, and more. The ramp signal is denoted by
"r(t)" in continuous-time and "r[n]" in discrete-time.

Continuous-Time (Analog) Domain:


r(t) = {
0, t < 0
t, t >= 0
}
Discrete-Time Domain:
r[n] = {
0, n < 0
n, n >= 0
}
In these formulas, t represents time in the continuous-time domain, and n
represents time indices in the discrete-time domain.

4. Exponential Signals : Exponential signals are signals that exhibit


exponential growth or decay characteristics over time in the continuous-
time domain or with time indices in the discrete-time domain.
Exponential signals are fundamental in various fields, including physics,
engineering, finance, and signal processing. They are often used to model
10
21BEC037 ROSHNI GHAI

processes that involve growth, decay, or attenuation.

Continuous-Time (Analog) Domain:


x(t) = A * e^(α * t)
Discrete-Time Domain:
x[n] = A * α^n
In these formulas:
t represents time in the continuous-time domain.
n represents time indices in the discrete-time domain.
A is the initial amplitude or value of the signal.
α is the exponential growth or decay factor.
Continuous-Time Exponential Signal: In the continuous-time case, the
signal x(t) grows or decays exponentially with time. The rate of growth or
decay is determined by the value of α.
Discrete-Time Exponential Signal: In the discrete-time case, the signal x[n]
also grows or decays exponentially with increasing time indices n. The
value of α controls the rate of growth or decay.

SAMPLING: In the context of signals and signal processing, sampling


refers to the process of converting a continuous-time signal, such as a cosine
signal, into a discrete-time signal by selecting and storing its values at specific
points in time. This is done in order to make the signal suitable for digital
processing and representation.
The sampling rate, often denoted as fs, is the number of
samples taken per second. It determines how finely the continuous signal is
"discretized." The Nyquist-Shannon sampling theorem states that in order to
accurately represent a continuous signal without introducing aliasing, the
sampling rate must be at least twice the highest frequency present in the signal.
The number of samples taken over a specific time interval
determines how detailed the digital representation of the signal will be. More
samples provide better accuracy but also require more storage and
computational resources.
5. Cosine Signal and it’s Sampling :
A cosine signal is a mathematical function that describes a waveform
with a repetitive oscillatory pattern, similar to the shape of a cosine
function. Mathematically, a cosine signal can be represented as:
x(t)=A⋅cos(2πf⋅t+ϕ)
x(t) is the value of the cosine signal at time t.
A represents the amplitude of the cosine wave.
f is the frequency of the cosine wave in Hertz (cycles per second).
ϕ is the phase offset of the cosine wave.

11
21BEC037 ROSHNI GHAI

Mathematically, the sampled version of a continuous cosine signal can be


represented as:
x[n]=A⋅cos((2πfs/f)⋅n+ϕ)
Where:
 x[n] is the value of the sampled cosine signal at the n-th sample.
 fs is the sampling frequency.
 n represents the sample index.

6. Sine Signal and it’s Sampling : A sine signal is a mathematical


function that describes a waveform with a repetitive oscillatory pattern,
resembling the shape of a sine function. Mathematically, a sine signal can
be represented as:
x(t)=A⋅sin(2πf⋅t+ϕ)
Where:
 x(t) is the value of the sine signal at time t.
 A represents the amplitude of the sine wave.
 f is the frequency of the sine wave in Hertz (cycles per second).
 ϕ is the phase offset of the sine wave.
The sampled version of a continuous sine signal can be
represented mathematically as:
x[n]=A⋅sin((2πfs/f)⋅n+ϕ)
Where:
 x[n] is the value of the sampled sine signal at the n-th sample.
 fs is the sampling frequency.
 n represents the sample index.

PROCEDURE:
1. Open the MATLAB software on your computer.
2. Define a time vector that covers the desired time span of the signal.
3. Create the desired signal using mathematical functions
4. Use the stem(t, y) function to display the signal in discrete domain.Then
customize it using functions like xlabel, ylabel, title, and grid.
5. Repeat steps 2 to 4 for all the other types of signals .
6. Use the subplot(rows, columns, index) function to create a grid of
subplots and place each signal plot in a specific location within the grid.
7. Observe the waveforms obtained of different signals and analyse them.

12
21BEC037 ROSHNI GHAI

MATLAB CODE
%unit step signal
t = -5:0.1:5;
u_t = zeros(size(t));
for i = 1:length(t)
if t(i) >= 0
u_t(i) = 1;
else
u_t(i) =0;
end
end
subplot(3,2,1);
stem(t, u_t, 'b', 'LineWidth', 2);
xlabel('Time (t)');
ylabel('u(t)');
title('Unit Step Function');
%unit impulse signal
t = -5:0.1:5;
i_t = zeros(size(t));
for i = 1:length(t)
if t(i) == 0
i_t(i) = 1;
else
i_t(i) =0;
end
end
subplot(3,2,2);
stem(t, i_t, 'b', 'LineWidth', 2);
xlabel('Time (t)');
ylabel('d(t)');
title('Unit Impulse Function');
% unit ramp signal
t = -5:0.1:5;
r_t = zeros(size(t));

for i = 1:length(t)
if t(i) >= 0
r_t(i) = t(i);
end
end
subplot(3,2,3);
stem(t, r_t, 'b', 'LineWidth', 2);
xlabel('Time (t)');
13
21BEC037 ROSHNI GHAI

ylabel('r(t)');
title('Ramp Signal');
%exponential signals
t = -5:0.1:5;
a = 2;
x_t = zeros(size(t));

for i = 1:length(t)
if t(i) >= 0
x_t(i) = exp(a * t(i));
end
end
subplot(3,2,4);
stem(t, x_t, 'b', 'LineWidth', 2);
xlabel('Time (t)');
ylabel('e(t)');
title('Exponential Signal');

%cosine signal
A=1;
F= 2;
dt=0.001;
t=0:dt:1;
F_s= 8*F;
T_s= 1/F_s;
n=F_s;
n_1 =0:T_s:1;
x_s = A*cos(2*pi*F*n_1);
subplot(3,2,5)
stem(n_1,x_s);
xlabel('Samples(n)');
ylabel('Amplitude');
title('Discrete Cosine Signal');

%sine signal
A=1;
F= 2;
dt=0.001;
t=0:dt:1;
F_s= 8*F; T_s= 1/F_s;
n=F_s;
n_1 =0:T_s:1;
x_s = A*sin(2*pi*F*n_1);

14
21BEC037 ROSHNI GHAI

subplot(3,2,6)
stem(n_1,x_s);
xlabel("Samples (n)");
ylabel("Amplitude");
title("Discrete Sine Signal",'LineWidth',5);

OUTPUT WAVEFORM

RESULT: Different waveforms of the respective signals were obtained


successfully.

15
21BEC037 ROSHNI GHAI

EXPERIMENT 2
AIM: Write a MATLAB program to find the linear convolution of two discrete
signals.

THEORY:

Convolution: The convolution of two signals is a mathematical operation that


combines the information from two signals to produce a third signal. It's a
fundamental operation in signal processing and is used for various applications,
including filtering, system analysis, and solving differential equations.
Convolution is therefore the process by which one may compute the overlap of two
graphs.

For two functions F(n) and G(n), the convolution of the two is expressed and
given by the following mathematical expression.
In continuous time, the convolution of two continuous signals x(t) and h(t) is
defined as:

This operation involves sliding one signal (h(t)) over the other signal (x(t)) and
calculating the integral of their product at each point of overlap.

For two discrete signals x[n] and h[n], the convolution ]y[n] is defined as:

This operation involves sliding one signal (h[n]) over the other signal (x[n]) in
reverse order and calculating the sum of element-wise products at each step.

Linear Convolution
Linear Convolution is a means by which one may relate the output and input of an
LTI system given the system’s impulse response. It is required to convolve the input
signal with the impulse response of the system. the equation pf linear convolution is
as follows:

The reason why the expression is summed an infinite number of times is just to
ensure that the probability of the two functions overlapping is 1. The impulse
response is time-shifted endlessly so that during some duration of time, the two
functions will certainly overlap .

16
21BEC037 ROSHNI GHAI

PROCEDURE:
1. Open the MATLAB software on your computer.
2. Define the two input signals, x and h, that you want to convolve. These can
be represented as arrays in MATLAB.
3. Use the conv function to perform convolution on the input signals.
4. Then subplot the signals and observe it’s waveform.
5. Implement the logic of convolution function via for loops and if else
statements.
6. Again subplot the signals and observe their waveform.

MATLAB CODE:
Using ‘conv’ function
clc;
clear all;
close all;
x=[1,2,4,8,10,13];
h=[1,2,4,8,10,12,16,18,20];

subplot(3,1,1);
stem(x);
xlabel('n values ');
ylabel('Amplitude');
title("Input Signal x(n)");
disp('Input Signal x:');
disp(x);

subplot(3,1,2);
stem(h);
xlabel('n values ');
ylabel('Amplitude');
title("Input Signal h(n)");
disp('Input Signal h:');
disp(h);

subplot(3,1,3);
y= conv (x,h);
stem(y);
xlabel('n values ');
ylabel('Amplitude');
title("Convolution Output");
disp('Convolution Result y:');
disp(y);

17
21BEC037 ROSHNI GHAI

OUTPUT WAVEFORM

Convolution without ‘conv’ function


clc;
close all;
clear all;
% Define two input signals
x=[1,2,4,8,10,13];
h=[1,2,4,8,10,12,16,18,20];

subplot(3,1,1);
stem(x);
xlabel('n values ');
ylabel('Amplitude');
title(" Input Signal x(n)");
disp('Input Signal x:');
disp(x);

subplot(3,1,2);
stem(h);
xlabel('n values ');
ylabel('Amplitude');
title("Input Signal h(n)");
disp('Input Signal h:');

18
21BEC037 ROSHNI GHAI

disp(h);
% Lengths of the input signals
M = length(x);
N = length(h);
% Initialize the result array
y = zeros(1, M + N - 1);
% Perform convolution
for n = 1:M + N - 1
y(n) = 0;
for k = max(1, n - N + 1):min(M, n)
y(n) = y(n) + x(k) * h(n - k + 1);
end
end
subplot(3,1,3);
stem(y);
xlabel('n values ');
ylabel('Amplitude');
title("Convolution Result");
disp('Convolution Result y:');
disp(y);

OUTPUT WAVEFORM

RESULT: Convolution of the signals have been done successfully.

19
21BEC037 ROSHNI GHAI

EXPERIMENT 3
AIM: Write a MATLAB program to find the correlation of two signals.

THEORY: Correlation is the measure of similarity or degree of similarity


between two signals or a signal with itself.
The correlation between two discrete time signals, x[n] and y[n],
is a measure of how similar they are at different time instances. Mathematically,
the correlation between x[n] and y[n] at a particular lag m is given by the
formula:

Rxy[m]=∑nx[n]⋅y[n−m]

Here, Rxy[m] represents the correlation between x[n] and y[n] at lag m, and the
sum is taken over all possible time indices n.

Types of Correlation:
1. Auto-correlation: Auto-correlation measures how similar a signal is to
itself at different time lags. In this case, both x[n] and y[n] are the same
signal. The auto-correlation function is denoted as Rxx[m] or Ryy[m], and
it helps in analyzing the periodicity and repeating patterns within a signal.

The auto-correlation of a signal x[n] at lag m is given by:


Rxx[m]=∑n x[n]⋅x[n−m]

2. Cross-correlation: Cross-correlation is used to measure the similarity


between two different signals x[n] and y[n]. It provides information about
how well the signals match at different time lags. Cross-correlation is
particularly useful in applications like signal synchronization, pattern
recognition, and system identification. The cross-correlation function is
denoted as Rxy[m] or Ryx[m].

The cross-correlation between two signals x[n] and y[n] at lag m is given
by:
Rxy[m]=∑nx[n]⋅y[n−m]

PROCEDURE:
1. Open the MATLAB software on your computer.
2. Define the two input signals, x and y, that you want to correlate. These
can be represented as random arrays in MATLAB.

20
21BEC037 ROSHNI GHAI

3. Use the xcorr function to perform convolution on the input signals.


4. Then subplot the signals and observe it’s waveform.
5. Implement the logic of correlation function via for loops and if else
statements.
6. Again subplot the signals and observe their waveform.

MATLAB CODE
AUTOCORRELATION USING ‘xcorr’ FUNCTION
%% Auto Correlation of two signals
clc;
close all;
clear all;
x= randn(1,50);
subplot(2,1,1);
stem(x);
title("Input Signal");
xlabel('Sample');
ylabel('Amplitude');

y= xcorr(x);
subplot(2,1,2);
stem(y);
title(" Auto Correlation ");
xlabel('Sample');
ylabel('Auto Correlation Values ');

OUTPUT WAVEFORM

21
21BEC037 ROSHNI GHAI

CROSS CORRELATION USING ‘xcorr’ FUNCTION


clc;
clear all;
close all;

% input signal 1
x1= randn(1,30);
subplot(3,1,1);
stem(x1);
grid on;
title("Input Signal 1");
xlabel('Sample');
ylabel('Amplitude');

% input signal 2
x2=randn(1,40);
subplot(3,1,2);
stem(x2);
title("Input Signal 2");
xlabel('Sample');
ylabel('Amplitude');
grid on;

l1 = length(x1);
l2 = length(x2);

22
21BEC037 ROSHNI GHAI

if l1 > l2
x2 = [x2, zeros(1, l1 - l2)];
end

if l1 < l2
x1 = [x1, zeros(1, l2 - l1)];
end

l1 = length(x1);
l2 = length(x2);

% output signal
y= xcorr(x1,x2);
subplot(3,1,3);
stem(y);
title("Cross Correlation Output");
xlabel('Sample');
ylabel('Correlation Value');
grid on;

OUTPUT WAVEFORM

23
21BEC037 ROSHNI GHAI

CORRELATION WITHOUT USING ‘xcorr’ FUNCTION


clc;
close all;
clear all;

% INPUT SIGNAL 1
x = randn(1,30);
subplot(3, 1, 1);
stem(x);
title('Input Sequence x');
xlabel('Sample');
ylabel('Amplitude');
grid on;

% INPUT SIGNAL 2
y = randn(1,40);
subplot(3, 1, 2);
stem(y);
title('Input Sequence y (Flipped)');
xlabel('Sample');
ylabel('Amplitude');
grid on;

y = fliplr(y);

l1 = length(x);
l2 = length(y);

if l1 > l2
y = [y, zeros(1, l1 - l2)];
end

if l1 < l2
x = [x, zeros(1, l2 - l1)];
end

l1 = length(x);
l2 = length(y);
r = zeros(1, l1 + l2 - 1);

for n = 1 : l1 + l2 - 1
for k = 1 : l2
24
21BEC037 ROSHNI GHAI

if (n - k) >= 0 && (n - k) < l1


r(n) = r(n) + x(n - k + 1) * y(k);
end
end
end

subplot(3, 1, 3);
stem(r);
title('Correlation Output r');
xlabel('Sample');
ylabel('Correlation Value');
grid on;

sgtitle('Correlation of x and y');

OUTPUT WAVEFORM

COMMAND WINDOW:

25
21BEC037 ROSHNI GHAI

RESULT: Correlation of the signals have been done successfully.

EXPERIMENT 4
AIM: Write a MATLAB program to find the circular convolution of two
discrete signals.

SOFTWARE REQUIREMENT: MATLAB

THEORY: Circular convolution is a mathematical operation used in signal


processing and linear systems theory to combine two signals. Unlike linear
convolution, circular convolution assumes that the signals are periodic and wrap
around at the edges, creating a circular effect. This operation is often used in
applications where signals have periodic characteristics, such as audio and
image processing.
Formula for circular convolution:

Methods of Circular Convolution


Generally, there are two methods, which are adopted to perform circular
convolution and they are −
 Concentric circle method,
 Matrix multiplication method.

26
21BEC037 ROSHNI GHAI

Concentric Circle Method


Let x1(n) and x2(n) be two given sequences. The steps followed for circular convolution
of x1(n) and x2(n) are
Take two concentric circles. Plot N samples of x1(n) on the

circumference of the outer circle maintaining equal distance
successive points in anti-clockwise direction.
 For plotting x2(n), plot N samples of x2(n) in clockwise direction
on the inner circle, starting sample placed at the same point as
0th sample of x1(n).
 Multiply corresponding samples on the two circles and add them to
get output.
 Rotate the inner circle anti-clockwise with one sample at a time.
Matrix Multiplication Method
Matrix method represents the two given sequence x1(n) and x2(n) in matrix
form.
 One of the given sequences is repeated via circular shift of one
sample at a time to form a N X N matrix.
 The other sequence is represented as column matrix.
 The multiplication of two matrices give the result of circular
convolution.

PROCEDURE:
 Open the MATLAB software on your computer.
 Define the two input signals, x and h, that you want to convolve. These
can be represented as random arrays in MATLAB.
 Use the cconv function to perform convolution on the input signals.
 Then subplot the signals and observe it’s waveform.
 Implement the logic of correlation function via for loops and if else
statements.
 Again subplot the signals and observe their waveform.

MATLAB CODE :
% Using in-built function
clc;
close all;
x = [1,2,-1,0,1];
h = [1,2,3];
lx = length(x);
lh = length(h);
if (lx<lh)
x = [x,zeros(1,lh-lx)];

27
21BEC037 ROSHNI GHAI

else
h = [h,zeros(1,lx-lh)];
end
y_inbuilt = cconv(x,h,length(x));
% stem(y_inbuilt);

%% Without using in-built function


y=zeros(1,length(x));
for i = 0:length(x)-1
for j = 0:length(x)-1
H = h(rem(rem(length(x)-j,length(x))+i,length(x))+1);
y(i+1) = y(i+1) + x(j+1)*H;
end
end

subplot(221);
stem(x);
title('First Sequence');
xlabel('n');
ylabel('x(n)');

subplot(222);
stem(h);
title('Second Sequence');
xlabel('n');
ylabel('h(n)');

subplot(223);
stem(y_inbuilt);
title('Circular Convolution using in-built function');
xlabel('n');
ylabel('y(n)');

subplot(224);
stem(y);
title('Circular Convolution');
xlabel('n');
ylabel('y(n)');

OUTPUT WAVEFORM:

28
21BEC037 ROSHNI GHAI

RESULT: Circular Convolution of the signals have been done successfully.

29

You might also like