Exp 9 :-To obtain standard Huffman code and code efficency using MATLAB , a DMS generates symbols a,b,c with probability.
%% Huffman Code
clc;
clear all;
close all;
% Inputs
unique_chars = ['a' 'b' 'c' 'd' 'e']
probabilities = [0.2 0.4 0.25 0.1 0.05]
% Initialize cell array for codewords
n = length(probabilities);
codewords = cell(1, n);
% Track matrix relationships
temp_prob = probabilities;
tree = cell(1, n);
for i = 1:n
tree{i} = i;
end
% Combine nodes until only one tree root remains
while length(temp_prob) > 1
% Sort probabilities in ascending order
[temp_prob, idx] = sort(temp_prob);
tree = tree(idx);
% Assign binary digits to paths
left_nodes = tree{1};
right_nodes = tree{2};
for idx_l = left_nodes
codewords{idx_l} = ['0', codewords{idx_l}];
end
for idx_r = right_nodes
codewords{idx_r} = ['1', codewords{idx_r}];
end
% Merge the lowest two probabilities
new_prob = temp_prob(1) + temp_prob(2);
new_node = [left_nodes, right_nodes];
% Rebuild arrays
temp_prob = [new_prob, temp_prob(3:end)];
tree = [{new_node}, tree(3:end)];
end
% Print results
fprintf('\n--- Huffman Codebook ---\n');
for i = 1:length(unique_chars)
fprintf("Character: '%c' -> Code: %s\n", ...
unique_chars(i), codewords{i});
end
exp 10 :- To encode and decode linear block codes using MATLAB.
%% Linear Block Code
clc;
clear all;
close all;
%% Encoder
disp('======= Generator Matrix =======');
disp('Parity Matrix');
P = [1 1 0; 0 1 1; 1 0 1; 1 1 1]
disp('Generator Matrix');
G = [eye(4,4), P]
%% Encoder
disp('======= Encoder =======');
disp('Data');
D = [1 1 0 1];
disp('Code');
C = mod(D*G, 2);
%% Decoder
disp('======= Decoder =======');
disp('Error Pattern');
E = [0 0 0 1 0 0 0];
disp('Received Code');
R = mod((C + E), 2);
disp('H Transpose');
HT = [P; eye(3)];
disp('Syndrome');
S = mod(R*HT, 2);
if all(S == 0)
disp('=== No Error in received message ===');
disp('Decoded Data');
D_received = R(1:4);
else
disp('=== Error in received message ===');
disp('Location of error bit');
[tf, index] = ismember(S, HT, 'rows');
disp(index);
disp('Corrected Received Message');
Error = zeros(1,7);
Error(index) = 1;
R_corrected = mod((R + Error), 2);
disp(R_corrected);
disp('Decoded Data');
D_received = R_corrected(1:4);
end