MATLAB Basics for DSP Applications
MATLAB Basics for DSP Applications
IT 7th Semester
SG22817
1
INDEX
2
EXPERIMENT NO:1
INTRODUCTION TO MATLAB AND ITS TOOLS
AIM: To study MATLAB software, its working environment, basic commands, and available
tools used for Digital Signal Processing applications.
THEORY:
MATLAB stands for Matrix Laboratory. It is a high-performance language that is used for
technical computing. It was developed by Cleve Molar of the company MathWorks. INC in
the year [Link] is written in C, C++, Java. It allows matrix manipulations, plotting of
functions, implementation of algorithms and creation of user interfaces. It is both a
programming language as well as a programming environment. It allows the computation of
statements in the command window itself.
The built-in functions of MATLAB offer top-notch resources for performing calculations,
including optimization, linear algebra, numerical solution of ordinary differential equations
(ODEs), data analysis, quadrate, signal processing, and many other scientific tasks. Modern
algorithms are used for the majority of these functions. There are many of these for both
animations and 2- D and 3-D graphics. MATLAB also supports an external interface.
The user can create their own functions in the MATLAB language. Thus, they are not
restricted to using only the built-in functions. Additional toolboxes are provided by
MATLAB. These toolboxes were created for common uses such as neural networks, symbolic
computations, image processing, control system design, and statistics.
The various uses of MATLAB are: Developing algorithms, performing linear algebra that is
linear, Graph plotting for larger data sets, Data visualization and analysis, Numerical Matrix
Computation .
3
MATLAB ENVIRONMENT COMPONENTS
Component Description
Command Window Executes commands directly
Command History Stores previously executed commands
Workspace Shows stored variables
Editor Window Used to write scripts (.m files)
Current Folder Shows files in your working directory
Figure Window Displays plots and graphical outputs
Simulink Library Graphical environment for simulations
Function Description
disp() The values or the text printed within single quotes is displayed on the
output screen.
clear To clear all variables
close all To close all graphics window
clc To clear the command window
exp(x) To compute the exponential value of x to the base e
abs(x) To compute the absolute value of x
sqrt(x) To compute the square root of x
log(x) To compute the logarithmic value of x to the base e
log10(x) To compute the logarithmic value of x to the base 10
rem(x, y) To compute the remainder of x/y
sin(x) To compute the sine of x
cos(x) To compute the cosine of x
tan(x) To compute the tangent of x
PROCEDURE
4
➢ Run the script and observe output.
➢ Plot a basic graph using commands in Command Window.
MATLAB PROGRAM:
clc;
clear;
close all;
x = 0:0.1:10;
y = sin(x);
plot(x, y);
title('Sine Wave');
xlabel('Time');
ylabel('Amplitude');
grid on;
OUTPUT:
A graphical sine wave is displayed in the figure window.
• X-axis → Time
• Y-axis → Amplitude
5
6
EXPERIMENT NO:2
BASIC MATHEMATICAL OPERATIONS IN MATLAB
➢ Arithmetic Operations
Operation Symbol Example
Addition + a+b
Subtraction - a-b
Multiplication * a*b
Division / a/b
Exponential / Power ^ a^2
➢ Element-wise Operations
To perform element-by-element operations in matrices, MATLAB uses a dot (.) before the
operator:
Operation Symbol Example
Element-wise Multiply .* A .* B
Element-wise Divide ./ A ./ B
Element-wise Power .^ A.^2
7
➢ Matrix Operations
➢ Matrix multiplication → A * B
➢ Transpose → A'
➢ Determinant → det(A)
➢ Inverse → inv(A)
PROCEDURE:
➢ Open MATLAB software.
➢ In the Command Window or Editor, define two numbers and perform arithmetic
operations.
➢ Define single-dimensional or two-dimensional matrices.
➢ Perform element-wise and matrix operations using respective commands.
➢ Observe and note the results.
MATLAB PROGRAM:
clc;
clear;
close all;
8
A = [1 2; 3 4];
B = [5 6; 7 8];
disp(' ');
disp('------ MATRIX OPERATIONS RESULTS ------');
disp('Matrix A:');
disp(A);
disp('Matrix B:');
disp(B);
9
OUTPUT:
• Arithmetic results display scalar outputs.
• Matrix operations display respective 2×2 outputs.
• Determinant and inverse produce numeric results based on matrix A.
10
ADVANTAGES OF MATLAB
➢ Easy to use interface: A user-friendly interface with features you want to use is one
click away.
➢ A large inbuilt database of algorithms: MATLAB has numerous important algorithms
you want to use already built-in, and you just have to call them in your code.
➢ Extensive data visualization and processing: We can process a large amount of data in
MATLAB and visualize them using plots and figures.
➢ Debugging of codes easy: There are many inbuilt tools like analyser and debugger for
analysis and debugging of codes written in MATLAB.
➢ Easy symbolic manipulation: We can perform symbolic math operations in MATLAB
using the symbolic manipulation algorithms and Tools in MATLAB.
DISADVANTAGES OF MATLAB
➢ MATLAB is slow since it is an interpreted language that is MATLAB programs are
not converted into Machine language but are run by external software, so it can
sometimes be slow.
➢ We cannot create the OUTPUT file in MATLAB.
➢ One cannot use graphics in MATLAB with -nojvm option, on doing so, we will get a
runtime error.
➢ We cannot make functions in one single .m file as we have in the case of other
programming languages. We have to create different files for different functions.
➢ Sometimes, the error messages are not much informative, so you have to figure out
the error yourself
11
EXPERIMENT NO:3
INTRODUCTION TO DSP
AIM: To study the basics of Digital Signal Processing, the concept of signals, types of
systems, and the need for digital processing.
SOFTWARE USED: MATLAB
THEORY
Digital Signal Processing (DSP) is a branch of engineering that focuses on the analysis,
modification, and manipulation of signals using digital systems or computers. A signal is
defined as any physical quantity that changes over time, space, or another independent
variable. Examples include sound waves varying with time, temperature changing across
different days, voltage changing across circuits, or images that vary in brightness from pixel
to pixel.
DSP is based on mathematical algorithms that operate on signals represented in numerical
(digital) form. These algorithms perform operations such as filtering, smoothing,
compression, feature extraction, noise removal, amplification, and pattern recognition.
12
TYPES OF SIGNALS:
Type Example
Continuous-time Human voice (real-time)
Discrete-time Sampled data
Analog Temperature, sound
Digital 0s and 1s representation
MATLAB PROGRAM:
clc;
clear;
close all;
t = 0:0.01:2*pi;
x = sin(t);
plot(t, x);
title('Sine Wave Signal');
xlabel('Time');
ylabel('Amplitude');
grid on;
OUTPUT
A sine wave is displayed, representing a basic periodic signal used in DSP applications.
13
14
EXPERIMENT NO:4
STUDY OF SAMPLING THEOREM EFFECT OF UNDER SAMPLING
AIM:
This experiment enables a student to learn
➢ How to view the real life analog signal with an oscilloscope.
➢ How to set the amplitude, frequency and phase of the signal source.
➢ How to set the sampling frequency of the source such that the signal is exactly
reconstructed from its samples. The principal objective of this experiment is to
understand the principle of sampling of continuous time analog signal.
THEORY:
𝑓𝑠 ≥ 2𝑓𝑚𝑎𝑥
Where:
• fs = Sampling frequency
• fmax = Highest frequency present in the signal
NEED OF SAMPLING:
Real-world signals are analog, but storing, processing, transmitting, and analyzing them is
easier and more reliable in digital form. Sampling is the first step in converting analog to
digital.
15
EFFECT OF UNDER-SAMPLING(ALIASING)
When the sampling rate is less than twice the maximum frequency, samples overlap and
create a false frequency called aliasing.
This makes the digital signal appear slower or incorrect when reconstructed. Aliasing causes:
• Signal distortion
• Wrong frequency representation
• Loss of original information
To avoid aliasing, an anti-aliasing filter is used before ADC to remove frequencies higher
than half the sampling frequency.
PROCEDURE:
MATLAB PROGRAM:
clc;
clear;
close all;
% Nyquist Sampling
fs1 = 2 * fm;
ts1 = 0:1/fs1:1;
x1 = sin(2*pi*fm*ts1);
% Under-sampling
fs2 = 0.8 * fm;
ts2 = 0:1/fs2:1;
x2 = sin(2*pi*fm*ts2);
subplot(3,1,1);
plot(t, x);
16
title('Original Continuous-Time Signal');
subplot(3,1,2);
stem(ts1, x1);
title('Sampling at Nyquist Rate');
subplot(3,1,3);
stem(ts2, x2);
title('Under-Sampling (Aliasing)');
OUTPUT:
• When sampled at the Nyquist rate, the sampled points correctly represent the original
signal.
• When sampling is below the Nyquist rate, the reconstructed signal appears distorted
and slower — this is due to aliasing.
17
EXPERIMENT NO:5
STUDY OF QUANTIZATION OF CONTINUOUS -AMPLITUDE DISCRETE- TIME
ANALOG SIGNALS
AIM:
This experiment enables a student to learn
• How to set the number of levels of a quantizer
• Calculate the error involved after quantization of the signal.
The principal objective of this experiment is to understand the principle of quantization of
continuous-amplitude discrete-time analog signals
THEORY
PROCESS OF QUANTIZATION
• Sampling converts continuous-time signal to discrete-time.
• Quantization converts continuous amplitude values to discrete levels.
• Encoding converts each quantized value into binary representation.
TYPES OF QUANTIZATION
Type Description
Uniform Quantization Equal step size for all levels
Non-Uniform Small steps for low amplitude, large for high amplitude (used in
Quantization speech coding)
Uniform quantization is most commonly used in digital communication and audio processing.
QUANTIZATION LEVELS
The number of possible amplitude levels depends on the number of bits (n):
𝐿 = 2𝑛
Where:
18
• L = Total quantization levels
• n = Number of bits per sample
The quantization step size (Δ) is calculated as:
𝑉𝑚𝑎𝑥 − 𝑉𝑚𝑖𝑛
Δ=
𝐿
QUANTIZATIONERROR/NOISE
If more quantization levels (more bits) are used → error reduces and quality improves.
PROCEDURE:
➢ Generate a discrete-time sampled signal in MATLAB.
➢ Define number of quantization levels (L).
➢ Apply quantization and round sample values to nearest level.
➢ Compare original and quantized signal.
➢ Compute quantization error.
MATLAB PROGRAM
clc;
clear;
close all;
t = 0:0.001:1;
x = sin(2*pi*5*t); % Original signal
n = 3; % Number of bits
L = 2^n; % Quantization levels
xmin = min(x);
xmax = max(x);
delta = (xmax - xmin) / L; % Step size
subplot(3,1,1);
plot(t,x);
title('Original Signal');
19
subplot(3,1,2);
stairs(t,xq);
title('Quantized Signal');
subplot(3,1,3);
plot(t,error);
title('Quantization Error');
OUTPUT:
➢ The quantized signal appears in stepped form compared to the original smooth signal.
➢ Quantization error is observed as the difference which decreases by increasing the
number of levels.
20
EXPERIMENT NO:6
STUDY OF DIFFERENT TYPES OF COMMANDING TECHNIQUES
THEORY:
In communication systems, especially voice transmission, the signal level varies widely—low
amplitude signals may be lost in noise while high amplitude signals dominate.
WHY COMMANDING?
When uniform quantization is applied to speech signals, weak voice signals suffer heavy
distortion.
Companding improves:
Parameter Improvement
SNR Higher for small signals
Transmission Less distortion
Bit efficiency Better usage
Storage Reduced data
21
1. A-Law Companding Formula
For compression:
𝐴∣𝑥∣ 1
, 0 ≤∣ 𝑥 ∣≤
𝐹(𝑥) = { 1 + ln 𝐴 𝐴
1 + ln (𝐴 ∣ 𝑥 ∣) 1
, ≤∣ 𝑥 ∣≤ 1
1 + ln 𝐴 𝐴
PROCEDURE
1. Input a set of voice/sine samples in MATLAB.
2. Apply A-law compression formula to the signal.
3. Apply μ-law compression formula to the signal.
4. Pass compressed data through simulated quantizer.
5. Expand signals to original amplitude.
6. Compare compressed & expanded waveform with original.
MATLAB PROGRAM
clc;
clear;
close all;
% Input Signal
22
t = 0:0.001:1;
x = sin(2*pi*5*t);
% A-Law Companding
A = 87.6;
yA = zeros(size(x));
for i = 1:length(x)
if abs(x(i)) < (1/A)
yA(i) = (A * abs(x(i))) / (1 + log(A));
else
yA(i) = (1 + log(A * abs(x(i)))) / (1 + log(A));
end
if x(i) < 0
yA(i) = -yA(i);
end
end
% Mu-Law Companding
mu = 255;
yM = sign(x).* log(1 + mu * abs(x)) ./ log(1 + mu);
% Plotting
subplot(3,1,1);
plot(t, x);
title('Original Signal');
ylabel('Amplitude');
subplot(3,1,2);
plot(t, yA);
title('A-Law Companded Signal');
ylabel('Amplitude');
subplot(3,1,3);
plot(t, yM);
title('Mu-Law Companded Signal');
xlabel('Time');
ylabel('Amplitude');
OUTPUT
23
24
EXPERIMENT NO:7
STUDY OF PROPERTIES OF LINEAR TIME -INVARIENT SYSTEM
• This experiment enables a student to give an idea of different properties of LTI System. The
principal objective of this experiment is to understand the Linearity and Time Invariant
Properties of a LTI System
THEORY:
A system in DSP is a device/mechanism that processes an input signal and produces an output
signal.
A system is called LTI (Linear Time-Invariant) if it satisfies two essential properties:
Property Meaning
Linearity Response to scaled and added inputs is same as scaling and adding
responses
Time- Output does not change if input signal is shifted in time
Invariance
LTI systems are extremely important in DSP because they can be analyzed using simple
mathematical methods such as convolution, and they accurately model many real-world
systems.
1. Linearity Property
A system is linear if it follows Superposition Principle:
𝑥1 (𝑡) → 𝑦1 (𝑡)
𝑥2 (𝑡) → 𝑦2 (𝑡)
25
2. Time-Invariance Property
A system is time-invariant if:
If the input is delayed by time 𝑡0 , then the output is also delayed by 𝑡0 , without any change in
shape:
𝑥(𝑡 − 𝑡0 ) → 𝑦(𝑡 − 𝑡0 )
PROCEDURE
➢ Define input signals in MATLAB.
➢ Define a system function (example: y[n] = x[n] + x[n−1]).
➢ Check linearity by applying individual and combined inputs.
➢ Check time-invariance by delaying input and comparing delayed output.
➢ Observe system response and verify properties.
MATLAB PROGRAM
clc;
clear;
close all;
n = 0:10;
x1 = sin(0.2*pi*n);
x2 = cos(0.2*pi*n);
26
% Individual Outputs
y1 = x1 + [0 x1(1:end-1)];
y2 = x2 + [0 x2(1:end-1)];
% Linearity Test
a = 2; b = 3;
x3 = a*x1 + b*x2;
y3 = x3 + [0 x3(1:end-1)];
y_check = a*y1 + b*y2;
figure;
subplot(2,2,1);
stem(n, y3, 'filled');
title('Output for a x_1[n] + b x_2[n]');
xlabel('n'); ylabel('y_3[n]');
subplot(2,2,2);
stem(n, y_check, 'filled');
title('a y_1[n] + b y_2[n]');
xlabel('n'); ylabel('y_{check}[n]');
27
subplot(2,2,3);
stem(n, y_delay_input, 'filled');
title('Output for delayed input x[n-1]');
xlabel('n'); ylabel('y_{delay\_input}[n]');
subplot(2,2,4);
stem(n, y_delay_output, 'filled');
title('Delayed version of y_1[n]');
xlabel('n'); ylabel('y_{delay\_output}[n]');
28
29
EXPERIMENT NO:8
STUDY OF CONVOLUTION SERIES AND PARALLEL SYSTEM
• [Link] Convolution
• [Link] (cascaded) connection of LTI systems.
• [Link] connection of LTI systems.
THEORY
Convolution is a fundamental mathematical operation used in Digital Signal Processing to
determine the output of an LTI (Linear Time-Invariant) system for any given input.
If x[n] is the input signal and h[n] is the impulse response of the system, then the output y[n]
is given by:
∞
This process slides the signal h[n] over the input x[n], multiplies, and sums them to get each
output point.
1. Linear Convolution
Linear convolution gives the exact output of an LTI system.
If:
• x[n] = input
• h[n] = impulse response
Then output length:
𝐿𝑒𝑛𝑔𝑡ℎ = (𝑙𝑒𝑛𝑔𝑡ℎ(𝑥) + 𝑙𝑒𝑛𝑔𝑡ℎ(ℎ) − 1)
30
ℎ𝑒𝑞 [𝑛] = ℎ1[𝑛] ∗ ℎ2[𝑛]
BLOCK DIAGRAMS
Series System
x[n] → [System 1] → [System 2] → y[n]
Parallel System
→ [System 1] →
x[n] → → + → y[n]
→ [System 2] →
PROCEDURE
1. Define two discrete signals and impulse responses in MATLAB.
2. Perform convolution to obtain the output.
3. For series system, convolve impulse responses to find equivalent response.
4. For parallel system, add individual responses to get total response.
5. Compare outputs graphically.
31
MATLAB PROGRAM
clc;
clear;
close all;
% Input Signal
x = [1 2 1];
% Linear Convolution
y = conv(x, h1);
% Series Connection
h_series = conv(h1, h2);
y_series = conv(x, h_series);
% Parallel Connection
y1 = conv(x, h1);
y2 = conv(x, h2);
y_parallel = y1 + y2;
subplot(3,1,1);
stem(y);
title('Linear Convolution Output y[n]');
subplot(3,1,2);
stem(y_series);
32
title('Series System Output');
subplot(3,1,3);
stem(y_parallel);
title('Parallel System Output');
OUTPUT
• Linear convolution gives the response of the system for a given input.
• In series connection, results show effect of merging two systems sequentially.
• In parallel connection, outputs add up, showing combined system behavior.
33
EXPERIMENT NO:9
STUDY OF DISCRETE FOURIER TRANSFORM(DFT) AND ITS INVERSE
SYSTEM
THEORY:
The Discrete Fourier Transform (DFT) is a mathematical technique used in DSP to convert a
discrete-time signal from the time domain into the frequency domain. The DFT analyzes the
frequency components present in a finite-duration signal.
If x[n] is a sequence of N samples, its DFT is given by:
𝑁−1
Where:
• X(k) = frequency-domain representation
• N = number of samples
• k = 0,1,...,N−1
This shows that DFT and IDFT form a reversible transformation—nothing is lost when both
are applied properly.
34
∣ 𝑋(𝑘) ∣= √(Real)2 + (Imag)2
APPLICATION OF DFT
Application Use
Audio processing Noise removal
Image processing Filtering, compression
Communication Modulation
Radar/SONAR Target detection
Medical ECG/EEG Pattern analysis
PROCEDURE
1. Input a discrete signal in MATLAB.
2. Apply DFT using the formula or fft() function.
3. Plot magnitude and phase spectrum.
4. Apply IDFT using ifft() to reconstruct original signal.
5. Compare input and reconstructed signals.
MATLAB PROGRAM
clc;
clear;
close all;
% Input Signal
x = [1 2 3 4];
N = length(x);
35
% DFT using FFT
X = fft(x);
subplot(3,1,1);
stem(abs(X));
title('Amplitude Spectrum');
subplot(3,1,2);
stem(phase);
title('Phase Spectrum');
subplot(3,1,3);
stem(real(x_reconstructed));
title('Reconstructed Signal using IDFT');
OUTPUT
• The amplitude spectrum displays the frequency magnitudes.
• The phase spectrum shows angle information of each frequency.
• The IDFT result and original signal match, demonstrating accurate reconstruction.
36
37
EXPERIMENT NO:10
STUDY OF TRANSFORM DOMAIN PROPERTIES AND ITS USE
THEORY:
In Digital Signal Processing, working in the transform domain allows signals to be analyzed in
terms of their frequency components instead of only time-based values. The Discrete Fourier
Transform (DFT) helps convert discrete-time signals from time domain to frequency domain.
The transform domain properties are useful to simplify computations, perform filtering, detect
periodic patterns, and understand signal characteristics.
1. Linearity Property
If:
𝑥1 [𝑛] ↔ 𝑋1 [𝑘], 𝑥2 [𝑛] ↔ 𝑋2 [𝑘]
3. Convolution Property
Linear convolution in time corresponds to multiplication in frequency domain:
𝑥[𝑛] ∗ ℎ[𝑛] ↔ 𝑋[𝑘] ⋅ 𝐻[𝑘]
38
WHY TRASNFORM DOMAIN IS USEFUL?
Reason Advantage
Analyze frequencies Understand periodic content
Fast filtering Convolution becomes multiplication
Data compression Used in JPEG, MP3
Noise reduction Identify and remove unwanted frequencies
PROCEDURE
1. Input a discrete signal in MATLAB.
2. Apply linearity property by combining signals and comparing results.
3. Perform circular shifting on the signal.
4. Compute DFT before and after shifting.
5. Compare the effect of shift in time with phase multiplication in frequency.
MATLAB PROGRAM
clc;
clear;
close all;
x = [1 2 3 4];
N = length(x);
% Linear Property
a = 2; b = 3;
x1 = [1 1 1 1];
x2 = [1 -1 1 -1];
X = fft(a*x1 + b*x2);
X_check = a*fft(x1) + b*fft(x2);
subplot(3,1,1);
stem(abs(X_original));
title('Original Signal Amplitude Spectrum');
39
subplot(3,1,2);
stem(abs(X_shift));
title('After Circular Shift - Amplitude Spectrum');
subplot(3,1,3);
stem(angle(X_shift));
title('Phase Change Due to Circular Shift');
OUTPUT
• The linearity test shows identical results for both computed transforms, confirming
linearity.
• Circular shifting of the signal changes the phase of the frequency components but not the
amplitude in most cases.
• Results prove that DFT properties simplify system analysis and signal manipulation.
40
EXPERIMENT NO:11
STUDY OF FIR FILTER DESIGN USING WINDOW METHOD:LOWPASS AND
HIGHPASS FILTER
THEORY:
A filter in DSP is used to allow certain frequencies to pass while blocking others. FIR (Finite
Impulse Response) filters are widely used because they are stable and have a linear phase
response.
TYPES OF FILTERS
WINDOW METHOD
The ideal impulse response of the filter is infinitely long. To make it practical, a window
function is multiplied to limit the length.
41
Common window functions:
Window Features
Rectangular Simple, poor side-lobe suppression
Hamming Good frequency response
Hanning Smoother than rectangular
Blackman Highest stop-band attenuation
PROCEDURE
➢ Select specifications (cut-off frequency, sampling rate, filter order).
➢ Apply window function to design FIR filter.
➢ Plot magnitude and phase responses.
➢ Test low-pass and high-pass filters with input signals.
➢ Observe frequency domain behavior.
MATLAB PROGRAM
freqz(h);
title('Low-Pass FIR Filter Using Hamming Window');
N = 40;
42
wc = 0.4*pi;
h = fir1(N, wc/pi, 'high', hamming(N+1));
freqz(h);
title('High-Pass FIR Filter Using Hamming Window');
OUTPUT
• The magnitude response of the low-pass filter shows attenuation of high frequencies while
allowing low frequencies to pass.
• The high-pass filter attenuates low-frequency components and passes higher frequencies.
43