0% found this document useful (0 votes)
38 views11 pages

shortened MATLAB codes (1)

The document demonstrates Pulse Code Modulation (PCM) and Differential Pulse Code Modulation (DPCM) using simple sinusoidal signals, including their encoding, quantization, and reconstruction processes. It also covers various modulation techniques such as Binary Amplitude Shift Keying (BASK), Binary Phase Shift Keying (BPSK), and Binary Frequency Shift Keying (BFSK), along with their demodulation methods. Additionally, it discusses source coding techniques like Huffman coding and Shannon-Fano coding, including the calculation of symbol entropy and coding efficiency.

Uploaded by

Harsh Kumar
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)
38 views11 pages

shortened MATLAB codes (1)

The document demonstrates Pulse Code Modulation (PCM) and Differential Pulse Code Modulation (DPCM) using simple sinusoidal signals, including their encoding, quantization, and reconstruction processes. It also covers various modulation techniques such as Binary Amplitude Shift Keying (BASK), Binary Phase Shift Keying (BPSK), and Binary Frequency Shift Keying (BFSK), along with their demodulation methods. Additionally, it discusses source coding techniques like Huffman coding and Shannon-Fano coding, including the calculation of symbol entropy and coding efficiency.

Uploaded by

Harsh Kumar
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/ 11

DEMONSTRATE PCM AND DPCM FOR ANY SIMPLE SINUSOIDAL

SIGNAL

PCM
td = 0.002; % Original sampling rate 500 Hz
t = 0:td:1; % Time interval of 1 second
xsig = sin(2*pi*t) - sin(6*pi*t); % 1Hz + 3Hz sinusoids
% Send the signal through a 16-level uniform quantizer
[s_out, sq_out, sqh_outl, ~, ~] = sampandquant(xsig, 16, td, 0.02);
figure;
subplot(2,1,1);
plot(t, xsig, 'k', t, sqh_outl(1:length(xsig)), 'b', 'LineWidth', 2);
title('Signal and its 16-level PCM signal');
xlabel('time (sec.)');
% Send the signal through a 4-level uniform quantizer
[s_out, sq_out, sqh_out2, ~, ~] = sampandquant(xsig, 4, td, 0.02);
subplot(2,1,2);
plot(t, xsig, 'k', t, sqh_out2(1:length(xsig)), 'b', 'LineWidth', 2);
title('Signal and its 4-level PCM signal');
xlabel('time (sec.)');
% Reconstruction of PCM signal
BW = 10; % Bandwidth is no larger than 10 Hz
H_lpf = zeros(1, 2^nextpow2(length(xsig)));
H_lpf(length(H_lpf)/2 - BW:length(H_lpf)/2 + BW - 1) = 1; % Ideal LPF
% Filtering and reconstruction
s_recvl = real(ifft(ifftshift(fftshift(fft(sqh_outl, length(H_lpf))) .*
H_lpf)));
s_recv2 = real(ifft(ifftshift(fftshift(fft(sqh_out2, length(H_lpf))) .*
H_lpf)));
figure;
subplot(2,1,1);
plot(t, xsig, 'b-', t, s_recvl(1:length(xsig)), 'b-.', 'LineWidth', 2);
legend('Original', 'Recovered');
title('Signal and filtered 16-level PCM signal');
xlabel('time (sec.)');
subplot(2,1,2);
plot(t, xsig, 'b-', t, s_recv2(1:length(xsig)), 'b-.', 'LineWidth', 2);
legend('Original', 'Recovered');
title('Signal and filtered 4-level PCM signal');
xlabel('time (sec.)');
function [s_out, sq_out, sqh_out1, Delta, SQNR] = sampandquant(sig_in, L, td,
ts)
if mod(ts/td, 1) == 0
nfac = round(ts/td);
p_zoh = ones(1, nfac);
s_out = downsample(sig_in, nfac);
Delta = (max(s_out) - min(s_out)) / L;
q_level = linspace(min(s_out) + Delta/2, max(s_out) - Delta/2, L);
% Quantize signal
sigp = (s_out - min(s_out)) / Delta + 1/2;
qindex = round(sigp);
qindex = min(qindex, L);
sq_out = q_level(qindex);
SQNR = 20 * log10(norm(s_out) / norm(s_out - sq_out));
s_out = upsample(s_out, nfac);
sqh_out1 = kron(sq_out, p_zoh);
sq_out = upsample(sq_out, nfac);
else
error('Error: ts/td is not an integer!');
end
end

DPCM
t = 0:0.01:1; % Time vector
a = 2; % Amplitude
fc = 2; % Frequency of the signal
xsig = a * sin(2*pi*fc*t); % Original sinusoidal signal
% Plot the original signal
subplot(6,1,1);
plot(t, xsig);
title('x(t) = a * sin(2 * pi * fc * t)');
% Sample the signal and generate a stem plot
subplot(6,1,2);
stem(t, xsig);
title('Sampled Signal');
% DPCM encoding
l = zeros(1, length(t)); % DPCM signal initialization
l(1) = 0; % Initial value
for N = 2:length(t)
if xsig(N) > xsig(N-1)
l(N) = 1;
elseif xsig(N) == xsig(N-1)
l(N) = 0;
else
l(N) = -1;
end
end
% Plot DPCM quantized signal
subplot(6,1,3);
stairs(t, l);
title('DPCM Quantized Signal');
% Dequantization (converting back to binary)
z2 = l + 1; % Map -1,0,1 to 0,1,2 (no need to convert to binary string)
subplot(6,1,4);
stem(t, z2);
title('Dequantized Signal');
% Low-pass filtering the DPCM signal for reconstruction
[b, a] = butter(2, 0.03, 'low');
k = filter(b, a, l);
% Plot the reconstructed signal
subplot(6,1,5);
plot(t, k);
title('Reconstructed Signal');

DIFFERENT MODULATION TECHNIQUES

BASK
x = [1 0 0 1 1 0 1]; % Binary Information
bp = 0.000001; % Bit period
disp('Binary information at Transmitter:');
disp(x);
% Generate the digital signal representation of binary information
bit = [];
for n = 1:length(x)
bit = [bit, x(n)*ones(1, 100)]; % Concatenate 1s and 0s as digital signal
end
t1 = bp/100:bp/100:bp*length(x);
subplot(3,1,1);
plot(t1, bit, 'LineWidth', 2.5); grid on;
axis([0 bp*length(x) -0.5 1.5]);
ylabel('Amplitude (Volt)');
xlabel('Time (sec)');
title('Transmitting information as digital signal');
% Binary-ASK modulation
A1 = 10; % Amplitude for 1
A2 = 5; % Amplitude for 0
f = 1/bp * 10; % Carrier frequency
m = [];
for i = 1:length(x)
m = [m, (x(i) == 1) * A1 * cos(2*pi*f*(bp/99:bp/99:bp)) + (x(i) == 0) * A2 *
cos(2*pi*f*(bp/99:bp/99:bp))];
end
t3 = bp/99:bp/99:bp*length(x);
subplot(3,1,2);
plot(t3, m);
xlabel('Time (sec)');
ylabel('Amplitude (Volt)');
title('Waveform for Binary ASK Modulation');
% Binary ASK Demodulation
mn = [];
ss = length(bp/99:bp/99:bp); % Length of each sample period
for n = 1:ss:length(m)-ss
y = cos(2*pi*f*(bp/99:bp/99:bp)); % Carrier signal
mm = y .* m(n:n+ss-1); % Multiply with modulated signal
z = trapz(bp/99:bp/99:bp, mm); % Integration
mn = [mn, round(2*z/bp) > 7.5]; % Demodulate to 1 or 0
end
disp('Binary information at Receiver:');
disp(mn);
% Representation of demodulated signal
bit = [];
for n = 1:length(mn)
bit = [bit, mn(n) * ones(1, 100)]; % Recreate digital signal after
demodulation
end
t4 = bp/100:bp/100:bp*length(mn);
subplot(3,1,3);
plot(t4, bit, 'LineWidth', 2.5); grid on;
axis([0 bp*length(mn) -0.5 1.5]);
ylabel('Amplitude (Volt)');
xlabel('Time (sec)');
title('Received information after Binary ASK Demodulation');

BPSK
% Binary Information
x = [1 0 0 1 1 0 1];
bp = 0.000001; % bit period
% Representation of transmitting binary information as digital signal
bit = [];
for n = 1:length(x)
if x(n) == 1
se = ones(1, 100);
else
se = zeros(1, 100);
end
bit = [bit se];
end
t1 = bp/100:bp/100:100*length(x)*(bp/100);
subplot(3, 1, 1);
plot(t1, bit, 'lineWidth', 2.5);
grid on;
axis([0 bp*length(x) -.5 1.5]);
ylabel('amplitude(volt)');
xlabel('time(sec)');
title('Transmitting Information as Digital Signal');
% Binary-PSK Modulation
A = 5; % Amplitude of carrier signal
br = 1/bp; % bit rate
f = br*2; % carrier frequency
t2 = bp/99:bp/99:bp;
ss = length(t2);
m = [];
for i = 1:length(x)
if x(i) == 1
y = A*cos(2*pi*f*t2);
else
y = A*cos(2*pi*f*t2 + pi);
end
m = [m y];
end
t3 = bp/99:bp/99:bp*length(x);
subplot(3, 1, 2);
plot(t3, m);
xlabel('time(sec)');
ylabel('amplitude(volt)');
title('Waveform for Binary PSK Modulation Corresponding Binary Information');
% Binary PSK Demodulation
mn = [];
for n = ss:ss:length(m)
t = bp/99:bp/99:bp;
y = cos(2*pi*f*t); % carrier signal
mm = y.*m((n-(ss-1)):n);
z = trapz(t, mm); % integration
zz = round((2*z/bp));
if zz > 0
a = 1;
else
a = 0;
end
mn = [mn a];
end
disp('Binary Information at Receiver:');
disp(mn);
% Representation of binary information as digital signal after PSK demodulation
bit = [];
for n = 1:length(mn)
if mn(n) == 1
se = ones(1, 100);
else
se = zeros(1, 100);
end
bit = [bit se];
end
t4 = bp/100:bp/100:100*length(mn)*(bp/100);
subplot(3, 1, 3);
plot(t4, bit, 'lineWidth', 2.5);
grid on;
axis([0 bp*length(mn) -.5 1.5]);
ylabel('amplitude(volt)');
xlabel('time(sec)');
title('Received Information as Digital Signal After Binary PSK Demodulation');

BFSK
x = [1 0 0 1 1 0 1];
bp = 0.000001;
% Representation of transmitting binary information as digital signal
bit = [];
for n = 1:length(x)
se = x(n)*ones(1, 100);
bit = [bit se];
end
t1 = bp/100:bp/100:100*length(x)*(bp/100);
subplot(3, 1, 1);
plot(t1, bit);
grid on;
axis([0 bp*length(x) -.5 1.5]);
title('Transmitting Information as Digital Signal');
% Binary-FSK Modulation
A = 5;
br = 1/bp;
f1 = br*8;
f2 = br*2;
t2 = bp/99:bp/99:bp;
m = [];
for i = 1:length(x)
if x(i) == 1
y = A*cos(2*pi*f1*t2);
else
y = A*cos(2*pi*f2*t2);
end
m = [m y];
end
t3 = bp/99:bp/99:bp*length(x);
subplot(3, 1, 2);
plot(t3, m);
title('Waveform for Binary FSK Modulation');
% Binary FSK Demodulation
mn = [];
t = bp/99:bp/99:bp;
y1 = cos(2*pi*f1*t);
y2 = cos(2*pi*f2*t);
for n = 100:100:length(m)
z1 = 0;
z2 = 0;
for j = 1:length(t)
z1 = z1 + y1(j)*m((j) + (n-100));
z2 = z2 + y2(j)*m((j) + (n-100));
end
z1 = z1*bp/99;
z2 = z2*bp/99;
if abs(z1) > abs(z2)
a = 1;
else
a = 0;
end
mn = [mn a];
end
disp('Binary Information at Receiver:');
disp(mn);
% Representation of binary information as digital signal after demodulation
bit = [];
for n = 1:length(mn)
se = mn(n)*ones(1, 100);
bit = [bit se];
end
t4 = bp/100:bp/100:100*length(mn)*(bp/100);
subplot(3, 1, 3);
plot(t4, bit);
grid on;
axis([0 bp*length(mn) -.5 1.5]);
title('Received Information as Digital Signal');

SOURCE CODING

HUFFMAN CODING
probabilities = [0.4 0.2 0.2 0.1 0.1];
probabilities = probabilities / sum(probabilities); % Normalize probabilities
set_contents = num2cell(1:length(probabilities)); % Initial set contents
set_probabilities = probabilities; % Set probabilities
% Initialize codewords as empty
codewords = cell(1, length(probabilities));
% Huffman coding process
while length(set_contents) > 1
[~, sorted_indices] = sort(set_probabilities); % Sort by probabilities
zero_set = set_contents{sorted_indices(1)};
one_set = set_contents{sorted_indices(2)};

% Assign 0 and 1 to the codewords for the sets


for idx = zero_set
codewords{idx} = [codewords{idx}, 0];
end
for idx = one_set
codewords{idx} = [codewords{idx}, 1];
end
% Merge the two sets and update probabilities
set_contents = [set_contents(sorted_indices(3:end)), { [zero_set, one_set]
}];
set_probabilities = [set_probabilities(sorted_indices(3:end)),
sum(set_probabilities(sorted_indices(1:2)))];
end
% Display the Huffman codewords
disp('Huffman Codewords:');
disp(codewords);
% Calculate the symbol entropy
entropy = -sum(probabilities .* log2(probabilities));
% Calculate the average Huffman codeword length
av_length = sum(cellfun(@length, codewords) .* probabilities);
% Calculate and display the efficiency
efficiency = entropy / av_length;
disp(['The symbol entropy is: ', num2str(entropy)]);
disp(['The average Huffman codeword length is: ', num2str(av_length)]);
disp(['The efficiency is: ', num2str(efficiency)]);

SHANNON FANO CODING:


probability_vec = [0.4, 0.2, 0.2, 0.1, 0.1];
probability_vec = probability_vec / sum(probability_vec); % Normalize
probabilities
n = length(probability_vec); % Number of symbols
coded = cell(1, n); % Cell array to store the codewords
sorted_prob = sort(probability_vec, 'descend'); % Sort probabilities in
descending order
symbols = 1:n; % Symbol indices
% Shannon-Fano coding algorithm
function [codewords, lengths] = shannon_fano(probabilities, symbols)
if length(probabilities) == 1
% Base case: only one symbol left, assign codeword '0'
codewords = {'0'};
lengths = [1];
return;
end
% Sort symbols and probabilities in descending order
[sorted_prob, sorted_indices] = sort(probabilities, 'descend');
sorted_symbols = symbols(sorted_indices);
total_sum = sum(sorted_prob);
cumulative_sum = cumsum(sorted_prob);
% Find the splitting point where the cumulative sum is closest to half
split_point = find(cumulative_sum >= total_sum / 2, 1);
% Split the set into two groups: left and right
left_prob = sorted_prob(1:split_point);
right_prob = sorted_prob(split_point+1:end);
left_symbols = sorted_symbols(1:split_point);
right_symbols = sorted_symbols(split_point+1:end);

% Recursively apply Shannon-Fano coding to the two groups


[left_codes, left_lengths] = shannon_fano(left_prob, left_symbols);
[right_codes, right_lengths] = shannon_fano(right_prob, right_symbols);
% Assign '0' to left codes and '1' to right codes
codewords = [cellfun(@(x) ['0', x], left_codes, 'UniformOutput', false), ...
cellfun(@(x) ['1', x], right_codes, 'UniformOutput', false)];
lengths = [left_lengths + 1, right_lengths + 1]; % Add 1 for the current bit
end
% Run Shannon-Fano coding
[codewords, lengths] = shannon_fano(probability_vec, symbols);
% Display the codewords and their lengths
disp('Shannon-Fano Codewords:');
for i = 1:n
fprintf('Symbol %d codeword: %s\n', i, codewords{i});
end
% Calculate entropy and average codeword length
entropy = -sum(probability_vec .* log2(probability_vec));
avg_length = sum(lengths .* probability_vec);
% Calculate efficiency
efficiency = entropy / avg_length * 100;
% Calculate variance of codeword lengths
variance_val = sum(probability_vec .* (lengths - avg_length).^2);
% Display results
disp(['The symbol entropy is: ', num2str(entropy)]);
disp(['The average Shannon-Fano codeword length is: ', num2str(avg_length)]);
disp(['The efficiency is: ', num2str(efficiency)]);
disp(['The variance is: ', num2str(variance_val)]);

DEMONSTRATE BER PERFORMANCE OF DIGITAL COMMUNICATION SYSTEM


EMPLOYING BASK, BPSK, BFSK MODULATION SCHEME YOU HAVE STUDIED AND
SHOW THE CONSTELLATION PLOT. (MATLAB/SIMULINK). ASSUME AWGN CHANNEL.

BASK
num_bit = 1000; % Number of bits
data = randi([0, 1], 1, num_bit); % Random bit generation (0 or 1)
SNRdB = 0:10; % SNR in dB
SNR = 10.^(SNRdB / 10); % Convert dB to linear scale
% BER (Bit Error Rate) calculation for different SNR values
for k = 1:length(SNRdB)
% Add noise to the signal using AWGN (Additive White Gaussian Noise)
y = awgn(complex(data), SNRdB(k)); % Complex data is used as input to AWGN
error = 0;
M = [];
% Compare received signal with original data to count errors
for c = 1:num_bit
if (y(c) > 0.5 && data(c) == 0) || (y(c) < 0.5 && data(c) == 1)
error = error + 1; % Increment error count
M = [M, ~data(c)]; % Flip the bit in the received signal
else
M = [M, data(c)]; % No error, keep the original bit
end
end
% Calculate error per bit
error = error / num_bit;
m(k) = error; % Store error rate for this SNR value
end
% Plot the simulation results
figure;
semilogy(SNRdB, m, 'o', 'LineWidth', 2.5); % Plot simulation results
grid on;
hold on;
% Calculate theoretical BER for Binary ASK modulation
BER_th = (1 / 2) * erfc(sqrt(SNR) / sqrt(2)); % Theoretical BER
semilogy(SNRdB, BER_th, 'r', 'LineWidth', 2.5); % Plot theoretical curve
grid on;
hold on;
% Add labels and title to the plot
title('Curve for Bit Error Rate vs SNR for Binary ASK Modulation');
xlabel('SNR (dB)');
ylabel('BER');
legend('Simulation', 'Theoretical');
axis([0 10 10^-5 1]); % Set axis limits

BPSK
bit_number = 1000;
data = randn(1, bit_number) > 0.5;
bpsk_data = 2 * data - 1;
noise = 1/sqrt(2) * (randn(1, bit_number) + 1i * randn(1, bit_number));
SNR = 0:9;
snr_lin = 10.^(SNR/10);
ber_sim = zeros(size(SNR));
ber_theory = 0.5 * erfc(sqrt(snr_lin));
for i = 1:length(SNR)
y = real(sqrt(snr_lin(i)) * bpsk_data + noise);
y = y >= 0;
ber_sim(i) = sum(abs(y - data)) / bit_number;
end
figure;
semilogy(SNR, ber_sim, 'b*-');
hold on;
semilogy(SNR, ber_theory, 'r+-');
grid on;
xlabel('Eb/N0');
ylabel('BER');
legend('Simulation', 'Theory');

BFSK
% Number of bits
N = 1000;
% Generate random binary data (0 or 1)
m = randi([0, 1], 1, N);
%% BFSK Modulation
x = zeros(1, N); % Initialize modulated signal
for i = 1:N
if m(i) == 0
x(i) = sqrt(-1); % For m = 0, set x(i) to -1 (complex)
else
x(i) = 1; % For m = 1, set x(i) to 1 (real)
end
end
% Plot BFSK modulated signal
figure;
scatterplot(x);
title('BFSK Modulated Signal');
%% AWGN Channel and Reception
ber_sim = []; % Simulation BER
ber_th = []; % Theoretical BER
% Loop over different Eb/N0 values in dB
for EbN0dB = 0:1:15
EbN0 = 10^(EbN0dB / 10); % Convert Eb/N0 from dB to linear scale
sigma = sqrt(1 / EbN0); % Noise standard deviation
% Generate noise with zero mean and unit variance
n = (1 / sqrt(2)) * (randn(1, N) + 1i * randn(1, N));
% Received signal (Add AWGN noise)
r = awgn(complex(x), EbN0dB); % Use awgn() to add noise to the signal
% Plot the received signal
figure;
scatterplot(r);
title(['Received Signal at Eb/N0 = ', num2str(EbN0dB), ' dB']);
% Decision device (compare the real part to the imaginary part)
m_cap = (real(r) > imag(r));
% BER calculation (Bit Error Rate)
noe = sum(m ~= m_cap); % Count errors (where m and m_cap do not match)
ber_sim1 = noe / N; % Simulated BER
ber_sim = [ber_sim, ber_sim1]; % Store simulation BER for this Eb/N0
% Theoretical BER for BFSK
ber_th1 = 0.5 * erfc(sqrt(EbN0 / 2)); % Theoretical BER formula
ber_th = [ber_th, ber_th1]; % Store theoretical BER
end
%% Plot BER vs Eb/N0
EbN0dB = 0:1:15; % Eb/N0 range in dB
% Plot the simulation and theoretical BER curves
figure;
semilogy(EbN0dB, ber_sim, 'r*-', EbN0dB, ber_th, 'bo-', 'LineWidth', 2);
xlabel('Eb/N0 (dB)');
ylabel('BER');
legend('Simulation', 'Theoretical');
grid on;
title('BER vs Eb/N0 for BFSK Modulation');

You might also like