[go: up one dir, main page]

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

Simulation Experiments-DC Lab

The document outlines experiments in a Digital Communication Lab, focusing on Gram-Schmidt orthogonalization, binary baseband signal simulation, and QPSK modulation and demodulation. It includes objectives, theoretical background, and MATLAB code for each experiment, demonstrating the processes of finding orthogonal basis vectors, estimating Bit Error Rate (BER) in an AWGN channel, and visualizing QPSK signals and constellations. The results from various outputs and plots are also presented to illustrate the findings.

Uploaded by

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

Simulation Experiments-DC Lab

The document outlines experiments in a Digital Communication Lab, focusing on Gram-Schmidt orthogonalization, binary baseband signal simulation, and QPSK modulation and demodulation. It includes objectives, theoretical background, and MATLAB code for each experiment, demonstrating the processes of finding orthogonal basis vectors, estimating Bit Error Rate (BER) in an AWGN channel, and visualizing QPSK signals and constellations. The results from various outputs and plots are also presented to illustrate the findings.

Uploaded by

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

Digital communication lab-BECL504 -

EXPERIMENT:05

GRAM-SCHMIDT ORTHOGONALIZATION: TO FIND ORTHOGONAL


BASIS VECTORS FOR THE GIVEN SET OF VECTORS AND PLOT THE
ORTHONORMAL VECTORS.

AIM:
To find orthogonal basis vectors for the given set of vectors and plot the orthonormal vectors

Theory:
Gram-Schmidt orthogonalization process is a method used in linear algebra to convert a set of
vectors into an orthogonal (perpendicular) set of vectors, while preserving the original span.
Once the vectors are orthogonal, they can be further normalized to produce an orthonormal set,
meaning the vectors are both perpendicular and have a unit length (magnitude = 1).

Code:
close all;
clc;
clear all;

% Ask for the number of vectors and their dimensions


num_vectors = input('Enter the number of vectors:');
dim = input('Enter the dimension of each vector: ');

% Initialize a matrix to store the input vectors


V = zeros(dim, num_vectors);

% Get the input vectors from the user


for i = 1:num_vectors
V(:, i) = input(['Enter vector ' num2str(i) ' as [x y z]: ']);
end

% Initialize matrices to store orthogonal and orthonormal vectors


U = zeros(size(V));
U_normalized = zeros(size(V));

% Gram-Schmidt Process to make the vectors orthogonal


for i = 1:num_vectors
U(:, i) = V(:, i); % Start with the current vector
for j = 1:i-1
% Subtract projections onto the previous orthogonal vectors
U(:, i) = U(:, i) - (dot(V(:, i), U(:, j)) / dot(U(:, j), U(:, j))) *
U(:, j);
end
% Normalize the vector to get orthonormal vectors
U_normalized(:, i) = U(:, i) / norm(U(:, i));

Dept. of Electronics & Telecommunication Engineering, BIT Page 25


Digital communication lab-BECL504 -

end

% Plotting the vectors


figure;
hold on;
colors = ['r', 'g', 'b', 'c', 'm']; % Colors for plotting

for i = 1:num_vectors
% Plot original vector
quiver3(0, 0, 0, V(1, i), V(2, i), V(3, i), colors(i), 'LineWidth', 2);

% Plot orthonormal vector


quiver3(0, 0, 0, U_normalized(1, i), U_normalized(2, i), U_normalized(3,
i), [colors(i) '--'], 'LineWidth', 2);
end

% Add labels and legend


xlabel('X-axis');
ylabel('Y-axis');
zlabel('Z-axis');
legend_text = arrayfun(@(i) {['v' num2str(i)], ['u' num2str(i) '
(orthonormal)']}, 1:num_vectors, 'UniformOutput', false);
legend([legend_text{:}]);
grid on;
axis equal;
title('Original and Orthonormal Vectors');
hold off;

% Display results in the command window


disp('Original Vectors:');
disp(V);
disp('Orthonormal Vectors:');
disp(U_normalized);

Output 1:

Enter the number of vectors:3


Enter the dimension of each vector: 3
Enter vector 1 as [x y z]: [1 2 3]
Enter vector 2 as [x y z]: [1 1 0]
Enter vector 3 as [x y z]: [0 1 1]
Original Vectors:
1 1 0
2 1 1
3 0 1

Orthonormal Vectors:
0.2673 0.6745 -0.6882
0.5345 0.4905 0.6882
0.8018 -0.5518 -0.2294

Dept. of Electronics & Telecommunication Engineering, BIT Page 26


Digital communication lab-BECL504 -

3D View- showing all 3 axes

Dept. of Electronics & Telecommunication Engineering, BIT Page 27


Digital communication lab-BECL504 -

Output 2:

Enter the number of vectors:3


Enter the dimension of each vector: 3
Enter vector 1 as [x y z]: [1 1 0]
Enter vector 2 as [x y z]: [1 0 1]
Enter vector 3 as [x y z]: [0 1 1]
Original Vectors:
1 1 0
1 0 1
0 1 1
Orthonormal Vectors:
0.7071 0.4082 -0.5774
0.7071 -0.4082 0.5774
0 0.8165 0.5774

3D View

Dept. of Electronics & Telecommunication Engineering, BIT Page 28


Digital communication lab-BECL504 -

EXPERIMENT: 06

SIMULATION OF BINARY BASEBAND SIGNALS USING A RECTANGULAR PULSE


AND ESTIMATE THE BER FOR AWGN CHANNEL USING MATCHED FILTER
RECEIVER.

AIM:

Simulation of binary baseband signals using a rectangular pulse and estimate the Bit Error Rate
for Additive White Gaussian Noise channel using matched filter receiver

THEORY:

Digital communication is the transmission of information using discrete (digital) signals, which
offers several advantages over analog communication, including improved noise resilience and
efficient use of bandwidth. In digital communication systems, binary data is encoded and
transmitted over various channels, with the quality of reception being critically impacted by
noise and interference. Baseband transmission refers to the direct transmission of digital signals
without any modulation to higher frequencies.

Pulse shaping is a crucial technique in digital communication to control the spectral properties of
the transmitted signal and reduce intersymbol interference (ISI). AWGN is a model used to
represent the impact of random noise on communication channels. It is characterized by having a
constant power spectral density and is additive in nature. The noise is normally distributed with
zero mean, significantly affecting the received signal's quality. The Bit Error Rate (BER)
quantifies the performance of a digital communication system by measuring the proportion of
transmitted bits that are incorrectly received. So a matched filter is a fundamental receiver design
that optimally processes signals received in the presence of noise. The filter is designed to
maximize the signal-to-noise ratio (SNR) at the time of sampling. For a rectangular pulse, the
matched filter has the same shape as the pulse itself. Its output is sampled at the symbol rate to
make a decision on the received bits:

If the output is above a threshold, the received bit is determined to be "1".


If it is below the threshold, it is determined to be "0".

Code:
clear all;
close all;
clc;
% Parameters
N = 1e5; % Number of bits
Eb_N0_dB = -10:2:10; % Eb/N0 in dB
Fs = 10; % Sampling frequency (samples per symbol)

Dept. of Electronics & Telecommunication Engineering, BIT Page 29


Digital communication lab-BECL504 -

pulse_duration = 1; % Duration of rectangular pulse (in symbol periods)

% Generate random binary data


data = randi([0 1], 1, N);

% Rectangular pulse shaping


pulse_shape = ones(1, Fs * pulse_duration); % Rectangular pulse
signal_tx = 2*data - 1; % BPSK signal (0 -> -1, 1 -> 1)
signal_tx = upsample(signal_tx, Fs); % Upsample
signal_tx = conv(signal_tx, pulse_shape, 'same'); % Pulse shaping

% Matched filter (same as pulse shape)


matched_filter = pulse_shape;

% Preallocate BER array


BER = zeros(1, length(Eb_N0_dB));

for i = 1:length(Eb_N0_dB)
% AWGN Channel (Eb/N0 -> SNR conversion)
Eb_N0 = 10^(Eb_N0_dB(i)/10);
noise_var = 1/(2*Eb_N0); % Noise variance
noise = sqrt(noise_var) * randn(1, length(signal_tx)); % AWGN

% Received signal with noise


signal_rx = signal_tx + noise;

% Apply matched filter at receiver


signal_rx_filtered = conv(signal_rx, matched_filter, 'same');

% Downsample and threshold detection


signal_rx_sampled = signal_rx_filtered(Fs/2:Fs:end); % Sample in middle
of each symbol
data_rx = signal_rx_sampled > 0; % Threshold
detection (BPSK)

% Compute BER
errors = sum(data ~= data_rx);
BER(i) = errors / N; % Compare transmitted and received bits

% Debugging output
fprintf('Eb/N0: %d, Errors: %d, BER: %f\n', Eb_N0_dB(i), errors, BER(i));
end

% Plot BER vs Eb/N0


figure;
semilogy(Eb_N0_dB, BER, 'bo-', 'LineWidth', 2);
xlabel('Eb/N0 (dB)');
ylabel('Bit Error Rate (BER)');
title('BER for Rectangular pulse for AWGN with Matched Filter Receiver');
grid on;

Output1:
Eb/N0: -10, Errors: 29265, BER: 0.292650
Eb/N0: -8, Errors: 27053, BER: 0.270530

Dept. of Electronics & Telecommunication Engineering, BIT Page 30


Digital communication lab-BECL504 -

Eb/N0: -6, Errors: 25786, BER: 0.257860


Eb/N0: -4, Errors: 25158, BER: 0.251580
Eb/N0: -2, Errors: 24998, BER: 0.249980
Eb/N0: 0, Errors: 25108, BER: 0.251080
Eb/N0: 2, Errors: 25082, BER: 0.250820
Eb/N0: 4, Errors: 24923, BER: 0.249230
Eb/N0: 6, Errors: 25226, BER: 0.252260
Eb/N0: 8, Errors: 24986, BER: 0.249860
Eb/N0: 10, Errors: 24965, BER: 0.249650

Output2:Eb/N0 range is from -20 to 10


Eb/N0: -20, Errors: 41498, BER: 0.414980
Eb/N0: -18, Errors: 39377, BER: 0.393770
Eb/N0: -16, Errors: 37025, BER: 0.370250
Eb/N0: -14, Errors: 34394, BER: 0.343940
Eb/N0: -12, Errors: 31619, BER: 0.316190
Eb/N0: -10, Errors: 29184, BER: 0.291840
Eb/N0: -8, Errors: 26886, BER: 0.268860
Eb/N0: -6, Errors: 25604, BER: 0.256040
Eb/N0: -4, Errors: 25156, BER: 0.251560
Eb/N0: -2, Errors: 25084, BER: 0.250840
Eb/N0: 0, Errors: 25056, BER: 0.250560
Eb/N0: 2, Errors: 24939, BER: 0.249390
Eb/N0: 4, Errors: 25073, BER: 0.250730
Eb/N0: 6, Errors: 25032, BER: 0.250320
Eb/N0: 8, Errors: 24908, BER: 0.249080
Eb/N0: 10, Errors: 24914, BER: 0.249140

Dept. of Electronics & Telecommunication Engineering, BIT Page 31


Digital communication lab-BECL504 -

Output3: Eb/N0 range is from -5 to 15


Eb/N0: -5, Errors: 25174, BER: 0.251740
Eb/N0: -3, Errors: 24853, BER: 0.248530
Eb/N0: -1, Errors: 25051, BER: 0.250510
Eb/N0: 1, Errors: 24923, BER: 0.249230
Eb/N0: 3, Errors: 25026, BER: 0.250260
Eb/N0: 5, Errors: 24851, BER: 0.248510
Eb/N0: 7, Errors: 24796, BER: 0.247960
Eb/N0: 9, Errors: 24704, BER: 0.247040
Eb/N0: 11, Errors: 25072, BER: 0.250720
Eb/N0: 13, Errors: 24799, BER: 0.247990
Eb/N0: 15, Errors: 24999, BER: 0.249990

Dept. of Electronics & Telecommunication Engineering, BIT Page 32


Digital communication lab-BECL504 -

EXPERIMENT: 07

PERFORM THE QPSK MODULATION AND DEMODULATION.


DISPLAY THE SIGNAL AND ITS CONSTELLATION.

AIM:
Perform the QPSK Modulation and demodulation. Display the signal and its constellation

THEORY:

Quadrature Phase Shift Keying (QPSK) is a modulation technique that conveys two bits of
information per symbol, making it more efficient than Binary Phase Shift Keying (BPSK).
QPSK utilizes four distinct phase shifts to represent four different symbols. Each symbol
corresponds to a unique pair of bits. This allows QPSK to effectively double the data rate
without increasing the bandwidth. QPSK uses two orthogonal carrier signals, In-phase (I) and
Quadrature (Q). These signals are typically sinusoidal and 90 degrees out of phase with each
other. The modulation process combines these carriers with the data to produce the QPSK signal.
In QPSK, two bits are grouped to form a symbol, leading to four possible symbols: (00, 01, 10,
11)

The constellation diagram provides a visual representation of the QPSK symbols in the I-Q
plane, illustrating the relationship between the phase shifts and the corresponding bit pairs. Each
point on the constellation diagram represents a unique symbol, and the distance between points
can indicate the potential for errors in noisy conditions. Each symbol is represented by a specific
phase in the constellation diagram:

o Symbol 00: Phase 0° (or 0 radians)


o
o
o Symbol 11'

CODE:
% QPSK Modulation
clc;
clear all;
close all;

% Generate Quadrature Carrier Signal


Tb = 1;
t = 0:(Tb/100):Tb;
fc = 1;
c1 = sqrt(2/Tb) * cos(2*pi*fc*t);
c2 = sqrt(2/Tb) * sin(2*pi*fc*t);

Dept. of Electronics & Telecommunication Engineering, BIT Page 33


Digital communication lab-BECL504 -

% Generate Message Signal


N = 8;
m = randi([0 1], 1, N); % Generate binary data (0 or 1)
t1 = 0;
t2 = Tb;
qpsk_signal = zeros(1, length(t) * N); % Preallocate for QPSK signal
symbols = []; % To store QPSK symbols

for i = 1:2:(N-1)
t = [t1:(Tb/100):t2];

% QPSK Mapping: Combine two bits to form a symbol


symbol = 2*m(i) + m(i+1); % Convert two bits to one symbol index (0 to
3)

% QPSK signal generation based on the symbol


switch symbol
case 0 % 00 -> (-1, -1)
m_s1 = -1 * ones(1, length(t)); % Modulate signal for (-1, -1)
m_s2 = -1 * ones(1, length(t));
case 1 % 01 -> (-1, 1)
m_s1 = -1 * ones(1, length(t)); % Modulate signal for (-1, 1)
m_s2 = ones(1, length(t));
case 2 % 10 -> (1, -1)
m_s1 = ones(1, length(t)); % Modulate signal for (1, -1)
m_s2 = -1 * ones(1, length(t));
case 3 % 11 -> (1, 1)
m_s1 = ones(1, length(t)); % Modulate signal for (1, 1)
m_s2 = ones(1, length(t));
end

% QPSK signal construction


qpsk_signal((i-1)*length(t)+1:i*length(t)) = c1 .* m_s1 + c2 .* m_s2;
% Store the constellation points for plotting
symbols = [symbols; m_s1(1), m_s2(1)]; % Capture the first point of each
symbol duration for constellation

% Plot the QPSK modulated signal


subplot(3, 2, 4); plot(t, qpsk_signal((i-1)*length(t)+1:i*length(t)));
title('QPSK Signal'); xlabel('t ---->'); ylabel('s(t)'); grid on; hold
on;
t1 = t1 + (Tb + 0.01);
t2 = t2 + (Tb + 0.01);
end
hold off;

% Plot the binary data bits and carrier signal


subplot(3, 2, 1); stem(m);
title('Binary Data Bits'); xlabel('n ---->'); ylabel('b(n)'); grid on;
subplot(3, 2, 2); plot(t, c1);
title('Carrier Signal 1'); xlabel('t ---->'); ylabel('c1(t)'); grid on;
subplot(3, 2, 3); plot(t, c2);
title('Carrier Signal 2'); xlabel('t ---->'); ylabel('c2(t)'); grid on;

% QPSK Demodulation

Dept. of Electronics & Telecommunication Engineering, BIT Page 34


Digital communication lab-BECL504 -

t1 = 0;
t2 = Tb;
demod = zeros(1, N);

for i = 1:N-1
t = [t1:(Tb/100):t2];
% Correlator
x1 = sum(c1 .* qpsk_signal((i-1)*length(t)+1:i*length(t)));
x2 = sum(c2 .* qpsk_signal((i-1)*length(t)+1:i*length(t)));
% Decision device
if (x1 > 0 && x2 > 0)
demod(i) = 1;
demod(i + 1) = 1;
elseif (x1 > 0 && x2 < 0)
demod(i) = 1;
demod(i + 1) = 0;
elseif (x1 < 0 && x2 < 0)
demod(i) = 0;
demod(i + 1) = 0;
elseif (x1 < 0 && x2 > 0)
demod(i) = 0;
demod(i + 1) = 1;
end
t1 = t1 + (Tb + 0.01);
t2 = t2 + (Tb + 0.01);
end

% Plot the QPSK demodulated bits


subplot(3, 2, 5); stem(demod);
title('QPSK Demodulated Bits'); xlabel('n ---->'); ylabel('b(n)'); grid on;

% QPSK Constellation Plot


subplot(3, 2, 6);
scatter(symbols(:, 1), symbols(:, 2), 'filled');
axis equal;
title('QPSK Constellation Diagram');
xlabel('In-Phase (I)');
ylabel('Quadrature (Q)');
grid on;
xlim([-2 2]);
ylim([-2 2]);
grid on;
hold on;

Dept. of Electronics & Telecommunication Engineering, BIT Page 35


Digital communication lab-BECL504 -

OUTPUT:

Dept. of Electronics & Telecommunication Engineering, BIT Page 36


Digital communication lab-BECL504 -

EXPERIMENT: 08
GENERATE 16-QAM MODULATION AND OBTAIN THE QAM
CONSTELLATION

AIM:
Generate 16-QAM Modulation and obtain the QAM constellation.

THEORY:
QAM is a widely used method of transmitting digital data over bandpass channels. QAM is a
popular choice because of its bandwidth efficiency and its ability to compensate for linear
channel distortion.

Introduction to 16-QAM Modulation and Noise Analysis


1. Overview of Digital Communication: Digital communication is a fundamental aspect of
modern telecommunications, enabling the transmission of information over various channels. As
data rates increase, the need for efficient modulation schemes that maximize the use of
bandwidth becomes essential. Quadrature Amplitude Modulation (QAM) is one such technique
that combines amplitude and phase modulation to convey data effectively.

2. What is 16-QAM? 16-QAM is a specific type of QAM that represents data using 16 distinct
symbols, each encoded as a unique combination of phase and amplitude. Each symbol
corresponds to 4 bits of information (since 24=162^4 = 1624=16), making it suitable for high-
rate data transmission. The constellation diagram for 16-QAM visualizes these symbols in the
complex plane, where the x-axis represents the in-phase component and the y-axis represents the
quadrature component. This diagram is crucial for understanding the performance of the
modulation scheme.

3. Importance of Noise in Communication: In real-world communication systems, signals are


inevitably affected by noise. Additive White Gaussian Noise (AWGN) is a common model used
to simulate the effects of noise in a communication channel. The presence of noise can lead to
errors in symbol detection, which affects the overall reliability of the communication system.
Analyzing how noise impacts the constellation diagram of a modulation scheme, like 16-QAM,
is vital for designing robust communication systems.

4. Objectives of the Experiment: This experiment aims to:

Generate a 16-QAM modulated signal from randomly generated bits.


Visualize the 16-QAM constellation diagram to understand the symbol representation.
Introduce AWGN to the modulated signal and observe the effects on the constellation
diagram.

Dept. of Electronics & Telecommunication Engineering, BIT Page 37


Digital communication lab-BECL504 -

Analyze how varying the Signal-to-Noise Ratio (SNR) affects the clarity of the
constellation points and the performance of the modulation scheme.

5. Expected Outcomes: By conducting this experiment, we expect to achieve a comprehensive


understanding of:

The 16-QAM modulation process and its efficiency in transmitting data.


The effect of noise on signal integrity, as evidenced by the changes in the constellation
diagram.
The relationship between SNR and signal quality, allowing for insights into optimizing
communication systems in noisy environments.

CODE:
close all;
clear all;
clc;
% Parameters
N = 1000; % Number of bits
M = 16; % 16-QAM
k = log2(M); % Number of bits per symbol (4 for 16-QAM)
SNR = 30; % Signal-to-Noise Ratio in dB

% Generate random bits


bits = randi([0 1], N, 1);

% Reshape bits into groups of k=4 bits (for 16-QAM)


symbols = reshape(bits, [], k);

% Convert binary to decimal for 16-QAM symbol mapping


symbols_dec = bi2de(symbols, 'left-msb');

% Modulate using 16-QAM


qam_modulated = qammod(symbols_dec, M);

% Add AWGN to the modulated signal


received_signal = awgn(qam_modulated, SNR, 'measured');

% Plot the received signal with colored points


scatterplot(received_signal, 1, 0, 'ro'); % Red circles for original
constellation points

% Add titles and labels


title(['16-QAM Constellation Diagram with AWGN (SNR = ', num2str(SNR), '
dB)']);
xlabel('In-phase Component');
ylabel('Quadrature Component');
grid on; % Enable grid for better visibility

Dept. of Electronics & Telecommunication Engineering, BIT Page 38


Digital communication lab-BECL504 -

OUTPUT1: SNR-30

OUTPUT 2: SNR- 0DB

Dept. of Electronics & Telecommunication Engineering, BIT Page 39


Digital communication lab-BECL504 -

OUTPUT 3: SNR - 100DB

Dept. of Electronics & Telecommunication Engineering, BIT Page 40


Digital communication lab-BECL504 -

EXPERIMENT:09
WRITE A MATLAB PROGRAM TO ENCODE BINARY DATA USING HUFFMAN
CODE AND DECODE IT.

AIM:
To write a MATLAB program to encode and decode binary data using Huffman code.

THEORY:

Huffman coding is a widely used method for lossless data compression, named after
David A. Huffman who introduced it in 1952. It's a variable-length prefix coding
algorithm used to compress data, where the most frequent symbols are represented using
shorter codes and the least frequent symbols are represented using longer codes.

Encoding the information before transmission is necessary to ensure data security and
efficient delivery of the information. The MATLAB program presented here encodes and
decodes the information and also outputs the values of entropy, efficiency and frequency
probabilities of characters present in the data stream.

Huffman algorithm is a popular encoding method used in electronics communication


systems. It is widely used in all the mainstream compression formats that you might
encounter from GZIP, PKZIP (winzip, etc) and BZIP2, to image formats such as JPEG
and PNG. Some programs use just the Huffman coding method, while others use it as one
step in a multistep compression process.

Huffman coding & deciding algorithm is used in compressing data with variable-length
codes. The shortest codes are assigned to the most frequent characters and the longest
codes are assigned to infrequent characters.

PROCEDURE:

Step 1. Compute the probability of each character in a set of data.


Step 2. Sort the set of data in ascending order.
Step 3. Create a new node where the left sub-node is the lowest frequency in the sorted list and
the right sub-node is the second lowest in the sorted list.
Step 4. Remove these two elements from the sorted list as they are now part of one node and add
the probabilities. The result is the probability for the new node.
Step 5. Perform insertion sort on the list.
Step 6. Repeat steps 3, 4 and 5 until you have only one node left.

Dept. of Electronics & Telecommunication Engineering, BIT Page 41


Digital communication lab-BECL504 -

Build the Huffman tree:

PROGRAM

%Write a MATLAB based program for encoding and decoding of Huffman code
clc;
clearall;
close all;
symbol =[1:5]; % Distinct data symbols appearing in
p = [0.4 0.2 0.2 0.1 0.1]; % Probability of each data
[dict,avglen]=huffmandict(symbol,p)
samplecode = dict{5,2} % Codeword for fifth signal value
dict{1,:}dict{2,:}dict{3,:}dict{4,:}dict{5,:}
hcode = huffmanenco(symbol,dict);
dhsig = huffmandeco(hcode,dict); % Decode the code.

Dept. of Electronics & Telecommunication Engineering, BIT Page 42


Digital communication lab-BECL504 -

disp('encoded msg:');
disp(hcode);
disp('decoded msg:');
disp(dhsig);
code_length=length(hcode)
sum=0;
for m=1:5
H=sum+(p(m)*log2(1/p(m)));
end
disp('H=');
disp(H);
Efficiency=(H/avglen)*100

Description

symbols: A cell array of symbols to be encoded.


probabilities: A vector of probabilities corresponding to each symbol. The probabilities should
sum up to 1.

The function returns a cell array dict, which is a Huffman dictionary containing symbols and
their corresponding Huffman codewords.This program defines two functions: huffmanenco is
used to encode data using the Huffman coding technique based on a given Huffman dictionary.
Huffman encoding replaces each symbol with its corresponding Huffman codeword from the
dictionary, resulting in a compressed representation of the data.and huffmandeco is used to
decode data that has been encoded using the Huffman coding technique, based on a given
Huffman dictionary. It takes the encoded data and the Huffman dictionary as input, returning the
decoded data.

Output:

Conclusion: Thus, Huffman coding efficiently represents the input data using variable-length
codes, achieving compression by using shorter codes for more frequent symbols.

Dept. of Electronics & Telecommunication Engineering, BIT Page 43


Digital communication lab-BECL504 -

EXPERIMENT:10
WRITE A MATLAB PROGRAM TO ENCODE BINARY DATA USING A (7,4)
HAMMING CODE AND DECODE IT.

AIM:

To write a MATLAB program to encode binary data using a (7,4) Hamming code and decode it.

THEORY:

The (7,4) Hamming code is an error-correcting code that allows the correction of single-bit
errors and the detection of two-bit errors. It operates on 4 bits of data and adds 3 parity bits to
form a 7-bit codeword.

Let's go through the steps to encode and decode a (7,4) Hamming code:

Encoding (4-bit data to 7-bit codeword):

1. Data Preparation: Let's assume we have a 4-bit data sequence (D3, D2, D1, D0).
2. Calculate Parity Bits (P0, P1, P2):
P0 is the parity bit for bits: D0, D1, D3
P1 is the parity bit for bits: D0, D2, D3
P2 is the parity bit for bits: D1, D2, D3
3. Insert Parity Bits: Place the calculated parity bits at their respective positions in the 7-bit
codeword.
4. Form the Codeword: The codeword is now composed of the original 4 bits of data and the 3
parity bits.

The resulting 7-bit codeword structure is as follows: Codeword=(P2,P1,D2,P0,D1,D0,P0)

Decoding (7-bit codeword to 4-bit data):

1. Calculate Syndrome Bits (S2, S1, S0):


S0 is the parity of bits: P0, D1, D0, P2, D2, P1.
S1 is the parity of bits: P1, D2, D1, P0, D0, P2.
S2 is the parity of bits: P2, D2, D1, P1, D0, P0.
2. Determine Error Position: Use the syndrome bits to identify the position of the error, if
any. The binary representation of the syndrome bits indicates the error position.
3. Correct Error: If an error is detected, correct the bit at the identified error position.
4. Extract Data Bits: Remove the parity bits to obtain the 4-bit original data.

Dept. of Electronics & Telecommunication Engineering, BIT Page 44


Digital communication lab-BECL504 -

Procedure:
Let's consider a 4-bit data: 1011 (D3, D2, D1, D0).

1. Calculate Parity Bits:


P0 (parity for bits: D0, D1, D3) = D0 xor D1 xor D3 = 1 xor 0 xor 1 = 0 (P0 is the
leftmost bit)
P1 (parity for bits: D0, D2, D3) = D0 xor D2 xor D3 = 1 xor 1 xor 1 = 1
P2 (parity for bits: D1, D2, D3) = D1 xor D2 xor D3 = 0 xor 1 xor 1 = 0
2. Insert Parity Bits:
Codeword: (0, 1, 1, 1, 0, 1, 0)

Now you have the encoded (7,4) Hamming codeword.

PROGRAM

%Simulation for encoding and decoding of a [7,4] Hamming code. The decoder
%can correct one error as shown and as theory states. The table at the end
%of the file shows the various outputs with different error positions and
%message bits. One error can be placed at any of the 7 bit locations and
%corrections made.

clc;
clearall;
close all;

n = 7%# of codeword bits per block


k = 4%# of message bits per block
P = [ 1 1 1;1 1 0;1 0 1;0 1 1 ];%Parity submatrix-Need binary(decimal combination of 7,6,5,3)
G = [ eye(k) P ]%Generator matrix
H = [ P' eye(n-k) ]%Parity-check matrix
% ENCODER%
msg = [ 1 1 1 1 ] %Message block vector-change to any 4 bit sequence
code = mod(msg*G,2)%Encode message
% CHANNEL ERROR(add one error to code)%
%code(1)= ~code(1);
code(2)= ~code(2);
%code(3)= ~code(3);
%code(4)= ~code(4);%Pick one,comment out others
%code(5)= ~code(5);
%code(6)= ~code(6);
%code(7)= ~code(7);
recd = code %Received codeword with error

% DECODER%

Dept. of Electronics & Telecommunication Engineering, BIT Page 45


Digital communication lab-BECL504 -

syndrome = mod(recd * H',2)


%Find position of the error in codeword (index)
find = 0;
for i = 1:n
if ~find
errvect = zeros(1,n);
errvect(i) = 1;
search = mod(errvect * H',2);
if search == syndrome
find = 1;
index = i;
end
end
end
disp(['Position of error in codeword=',num2str(index)]);
correctedcode = recd;
correctedcode(index) = mod(recd(index)+1,2)%Corrected codeword
%Strip off parity bits
msg_decoded=correctedcode;
msg_decoded=msg_decoded(1:4)

%Error position Syndrome Decimal 4 bit word codeworddmin


% 1 111 7 0000 0000000
% 2 110 6 0001 0001011 3
% 3 101 5 0010 0010101 4
% 4 011 3 0011 0011110 3
% 5 100 4 0100 0100110 3
% 6 010 2 0101 0101101 3
% 7 001 1 0110 0110011 4
%No error will give syndrome of 000 0111 0111000 3
% 1000 1000111 4
% 1001 1001100 3
% 1010 1010010 4
% 1011 1011001 3
% 1100 1100001 3
% 1101 1101010 3
% 1110 1110100 4
% 1111 1111111 3
%Any exclusive or additions of any two codewords should give another
%codeword.

Dept. of Electronics & Telecommunication Engineering, BIT Page 46


Digital communication lab-BECL504 -

In MATLAB, the eye function is used to create an identity matrix, which is a square matrix with
ones on the main diagonal and zeros elsewhere. Where n is the number of rows (and columns) in
the resulting identity matrix.

Output
n =7
k =4

G=

1 0 0 0 1 1 1
0 1 0 0 1 1 0
0 0 1 0 1 0 1
0 0 0 1 0 1 1

H=

1 1 1 0 1 0 0
1 1 0 1 0 1 0
1 0 1 1 0 0 1

msg =

1 1 1 1

code =

1 1 1 1 1 1 1

recd =

1 0 1 1 1 1 1

syndrome =

1 1 0

Position of error in codeword=2

Dept. of Electronics & Telecommunication Engineering, BIT Page 47


Digital communication lab-BECL504 -

correctedcode =

1 1 1 1 1 1 1

msg_decoded =

1 1 1 1

Conclusion: Thus a MATLAB program is written to encode and decode binary data using a
(7,4) Hamming code and results have been verified.

Dept. of Electronics & Telecommunication Engineering, BIT Page 48


Digital communication lab-BECL504 -

EXPERIMENT:11
WRITE A MATLAB PROGRAM TO ENCODE BINARY DATA USING A
((3,1,2)/SUITABLY DESIGNED) CONVOLUTION CODE AND DECODE IT

AIM:
To write a program to encode binary data using a ((3,1,2)/suitably designed) Convolution code
and decode it.

THEORY:
Creating a complete MATLAB program for encoding and decoding using a specific
convolutional code requires a significant amount of code and understanding of the specific code
parameters (rate, constraint length, generator polynomials, etc.). I'll provide you with a general
outline and steps to create the encoding and decoding processes for a (3,1,2) convolutional code.

Procedure: let's define the generator polynomials for a (3,1,2) convolutional code:

Generator polynomials:

g1=[1,0,1]
g2=[1,1,1]

Encoding:
1. Define the input binary data.
2. Set up the convolutional code parameters (generator polynomials, rate, constraint length,
etc.).
3. Use the convenc function to perform convolutional encoding on the input data.

Decoding:
1. Define the received encoded data (potentially with added noise or errors).
2. Set up the Viterbi decoder parameters (trellis structure, traceback depth, etc.).
3. Use the vitdec function to perform Viterbi decoding on the received encoded data.

CODE:
% Parameters for the (3,1,2) convolutional code
clc; clear all; close all;
K = 3;
G1 = 7;
G2 = 5;
msg = [1 1 0 0 1 0]
trel = poly2trellis(K,[G1 G2]);
coded = convenc(msg,trel);
tblen = length(msg);

Dept. of Electronics & Telecommunication Engineering, BIT Page 49


Digital communication lab-BECL504 -

decoded = vitdec(coded,trel,tblen,'trunc','hard')
disp('coded');
disp(decoded);

OR

% Parameters for the (3,1,2) convolutional code


constraint_length = 3;
generator_polynomials = [1 0 1; 1 1 1];
code_rate = 1/3;
t = poly2trellis(constraint_length, generator_polynomials);

% Define input binary data


input_data = [1 0 1 0 1]; % Example binary data

% Encoding using convolutional code


encoded_data = convenc(input_data, t);

% Add some noise or errors (optional, for simulation purposes)


received_data = encoded_data; % Simulated received data

% Decoding using Viterbi decoder


tb_depth = 12; %Traceback depth
decoded_data = vitdec(received_data, generator_polynomials, tb_depth, 'trunc', 'hard');

% Display results
disp('Original Data:');
disp(input_data);
disp('Encoded Data:');
disp(encoded_data);
disp('Received Data:');

In this example, convenc is used for encoding, andvitdec is used for decoding with a Viterbi
decoder. Make sure to adjust the input data, generator polynomials, and other parameters
based on your specific requirements for the convolutional code.

OUTPUT:

Dept. of Electronics & Telecommunication Engineering, BIT Page 50


Digital communication lab-BECL504 -

Conclusion: Thus a MATLAB program is written to encode binary data using a


((3,1,2)/suitably designed) Convolution code and decode it and results have been verified.
EXPERIMENT:12

FOR A GIVEN DATA, USE CRC-CCITT POLYNOMIAL TO OBTAIN THE CRC


CODE. VERIFY THE PROGRAM FOR THE CASES A) WITHOUT ERROR B) WITH
ERROR

AIM:
To obtain the CRC code for a given data using CRC-CCITT polynomial and to Verify the
program for the cases a) Without error b) With error

THEORY:
The cyclic redundancy check, or CRC, is a technique for detecting errors in digital data, but not
for making corrections when errors are detected. It is used primarily in data transmission.
This Cyclic Redundancy Check is the most powerful and easy to implement technique. CRC is
based on binary division. In CRC, a sequence of redundant bits, called cyclic redundancy check
bits, are appended to the end of data unit so that the resulting data unit becomes exactly divisible
by a second, predetermined binary number. At the destination, the incoming data unit is divided
by the same number. If at this step there is no remainder, the data unit is assumed to be correct
and is therefore accepted. A remainder indicates that the data unit has been damaged in transit
and therefore must be rejected. The CCITT CRC-16 polynomial (used in a variety of
applications) is represented by the polynomial x16+x12+x5+1, which corresponds to the hex value

simulate both cases: without error and with error in the received data.

Procedure:
1. Generate CRC for the given data using the CRC-CCITT polynomial.
2. Introduce an error in the data.
3. Recalculate CRC for the erroneous data.
4. Verify if the CRC detects the error.

Program
#include<stdio.h>
int a[100],b[100],i,j,len,k,count=0;

//Generator Polynomial:g(x)=x^16+x^12+x^5+1
int gp[]={1,0,0,0,1,0,0,0,0,0,0,1,0,0,0,0,1,};

int main()
{
void div();
printf("\nEnter the length of Data Frame :");
scanf("%d",&len);

Dept. of Electronics & Telecommunication Engineering, BIT Page 51


Digital communication lab-BECL504 -

printf("\nEnter the Message :");


for(i=0;i<len;i++)
scanf("%d",&a[i]);
//Append r(16) degree Zeros to Msg bits
for(i=0;i<16;i++)
a[len++]=0;
//Xr.M(x) (ie. Msg+16 Zeros)
for(i=0;i<len;i++)
b[i]=a[i];

//No of times to be divided ie. Msg Length


k=len-16;
div();
for(i=0;i<len;i++)
b[i]=b[i]^a[i]; //MOD 2 Substraction
printf("\nData to be transmitted : ");
for(i=0;i<len;i++)
printf("%2d",b[i]);

printf("\n\nEnter the Reveived Data : ");


for(i=0;i<len;i++)
scanf("%d",&a[i]);
div();

for(i=0;i<len;i++)
if(a[i]!=0)
{
printf("\nERROR in Recived Data");
return 0;
}
printf("\nData Recived is ERROR FREE");
}

void div()
{
for(i=0;i<k;i++)
{
if(a[i]==gp[0])
{
for(j=i;j<17+i;j++)
a[j]=a[j]^gp[count++];
}
count=0;
}
}

Dept. of Electronics & Telecommunication Engineering, BIT Page 52


Digital communication lab-BECL504 -

Output: a) Without error


Enter the length of data frame:4
Enter the message: 1
0
1
0
Data to be transmitted : 1 0 1 0 1 0 1 0 0 0 0 1 0 1 0 0 1 0 1 0
Enter the received data: 1 0 1 0 1 0 1 0 0 0 0 1 0 1 0 0 1 0 1 0
Data Recived is ERROR FREE.

Output: b) With error


Enter the length of data frame:4
Enter the message: 1
0
1
0
Data to be transmitted : 1 0 1 0 1 0 1 0 0 0 0 1 0 1 0 0 1 0 1 0
Enter the received data: 1 0 1 0 1 0 1 0 0 0 0 1 0 1 0 0 1 0 1 1
ERROR in Recived Data.

Conclusion: The CRC code is obtained for a given data using CRC-CCITT polynomial and the
program is verified for the cases a) Without error b) With error.

Dept. of Electronics & Telecommunication Engineering, BIT Page 53

You might also like